So i have a class that needs to be tested. Lets call it ClassToTest. It has a couple of Dao objects as fields.
Public class ClassToTest {
@Autowired
MyDao dao;
void methodToTest() {
dao.save(something);
}
}
As you can see ClassToTest does not contain any constructor or setter and I am using spring to autowire the fields.
Now, I have a base test class with all the dependencies that classToTest requires:
public abstract BaseTest {
@Mock
MyDao dao;
}
And the testClass extends this BaseTest class :
public class TestClass extends BaseTest {
@InjectMocks
ClassToTest classToTest = new ClassToTest();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
classToTest.methodToTest();
}
}
This results in a null pointer exception when the save happens. However, if i change setup method to this :
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
classToTest.dao = dao;
}
the test passes.
My understanding was that when a class does not have a constructor or a setter, InjectMocks would inject the mocks by using field injection. Why is that not happening here?
Aucun commentaire:
Enregistrer un commentaire