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.

@Component
 class Class1{
 private String str= "Some String";
 //getter setter
}

@Component
class Class2{

@Autowired
Class1 class1;
//getter setter
}

@Component
class Class3{

@Autowired
Class2 class2;
 //getter setter
}

public class TestClass{

@InjectMocks
Class3 class3;

@Spy
Class2 class2;

@Spy
Class1 class2;

    @Test
    public void simpleTest(){
    
    String s = class3.class2.class1.getStr();
    Assert.equals(s,"Some String");
    
    }
}

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

@RunWith(SpringRunner.class)
@SpringBootTest

over your test to make it use the actual context.

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