Search code examples
javajunitjmockit

Mocked method wraps exception in collection rather than throwing exception


I have a test using jmockit's result = new Object[] {...} that is failing. The jmockit version is 1.34. The test should throw an exception but instead jmockit is returning a collection with the exception in it. Here is an example:

public class ServiceTest {
    public class Service {
        private Set<String> saved;

        public Service() {
            saved = new HashSet<>();
            saved.add("one");
            saved.add("two");
        }

        public Set<String> readAll() {
            return Collections.unmodifiableSet(saved);
        }
    }

    @Test(expected = RuntimeException.class)
    public void testReadAll(@Mocked Service service) {
        new Expectations() {{
                service.readAll(); times = 1; result = new RuntimeException();
        }};

        service.readAll();
    }

    @Test
    public void testReadAllWithArray(@Mocked Service service) {
        new Expectations() {{
                service.readAll(); times = 1; result = new Object[]{new RuntimeException()};
        }};

        Set set = service.readAll();
        assertThat(set.iterator().next(), instanceOf(RuntimeException.class));
    }
}

testReadAllWithArray shows that the object returned by readAll is a set with the exception in it.

Is this a bug or is there any workaround?


Solution

  • Upgrade from jmockit 1.34 to the latest version.