Skip to content
Advertisement

Nested Autowired Dependencies not injected in Junits

Below is the code to demonstrate the issue. Class3 has autowired field Class2 and Class2 has autowired dependency of Class1, simpleTest to get the String value of Class1 using Class3. So in the test execution Class2 is not null and gets injected into Class3, but Class1 is null in Class2.

JavaScript

Advertisement

Answer

That’s because of the @Spy annotation you put over the Class2, it makes the Class2 a mock and not a valid Spring bean.

If you want to get Spring’s DI here, you’d have to get your beans with the @Autowired and maybe place

JavaScript

over your test to make it use the actual context.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement