jmockit / jmockit1

Advanced Java library for integration testing, mocking, faking, and code coverage
Other
458 stars 238 forks source link

Support for @Mock fields in JUnit5's @Nested classes #716

Open sinhote opened 2 years ago

sinhote commented 2 years ago

I've seen that if one uses a @Nested class containing fields annotated with @Mocked, those are not initialized (resulting in NPEs).

An obvious workaround is to move those fields to the outer class, but this somewhat goes against the spirit of nested classes, which allow to encapsulate related groups of tests. If the mocked fields are only relevant to the nested class, why should they be defined outside?

I've seen this was already reported in #458, but it was closed by simply saying "only fields in outer classes are supported by @Mock". Can this be reconsidered?

Here's a sample code demonstrating the issue:

class MockedNestedTest {
    @Nested
    class Field {
        @Mocked Foo foo;
        @Test
        void shouldInitializeField() {
            Assertions.assertNotNull(foo); // this fails
        }
    }

Thanks!