Basic problem:
When using @Mock
and @InjectMocks
in a test, you have to use @Spy
on all the beans you still want to inject normally. Problem is that this does not work with @Property
you can't use @Spy
on @Property
. But when there is no @Spy
the property value of "envValue" will be null. So what to do?
@MicronautTest
@Property(name = "someEnvName", value = "0")
public class TestFooBar {
@Spy
@Inject
private Foo foo; //bean that is injected inside Bar
@Mock
private ClassToBeMocked mocked; //bean that is injected inside Bar
@Spy
@Property(name = "someEnvName")
private Long envValue; //some property that is used in Bar. --> throws an error
@InjectMocks
private Bar bar; //class to test
Ok. The solution is like suggested on the micronaut docu
(https://micronaut-projects.github.io/micronaut-test/4.0.0-M8/guide/index.html#junit5)
Instead of using @Spy
on all "normal" implementations. I just had to use
@MockBean(ClassToBeMockedImpl.class)
public ClassToBeMocked classToBeMocked() {
return mock(ClassToBeMocked.class);
}
on the class I want o mock. So all the field injection were uncessary.