Java – mockito mock object returns null
•
Java
Hi, I'm trying to implement some tests for my JSF application and mocks. I use mockito (I also use springs)
@RunWith(MockitoJUnitRunner.class)
public class GeneralConfigServiceImpltest {
private GeneralConfigService generalConfigService;
@Mock
private GeneralConfigDAO generalConfigDAO;
@Mock
private GeneralConfig gen;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
generalConfigService = new GeneralConfigService();
ReflectionTestUtils.setField(generalConfigService,"generalConfigDAO",generalConfigDAO);
}
@Test
public void testAddGeneralConfigCallDAOSuccess() throws DAOException,EntityNullException,IllegalEntityArgumentException,ParseException,EntityPersistException {
gen = createGeneralConfigs("label","value");
generalConfigService.setInstance(gen);
generalConfigService.persist();
log.info(generalConfigService.getInstance().toString());
}
}
The test was successful, but when I wanted to retrieve the instance using the getInstance method All the parameters I set before (through the previous constructor) are null I'm a novice at mocking objects. Is this behavior normal or is my code wrong?
Solution
It actually depends on the implementation of generalconfigservice #getinstance() If you use the @ injectmocks annotation, you can also simplify the test code
When using mockitojunitrunner, you do not need to manually initialize mocks and inject dependencies:
@RunWith(MockitoJUnitRunner.class)
public class GeneralConfigServiceImpltest {
@InjectMocks
private GeneralConfigService generalConfigService;
@Mock
private GeneralConfigDAO generalConfigDAO;
@Test
public void testAddGeneralConfigCallDAOSuccess() {
// generalConfigService is already instantiated and populated with dependencies here
...
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
