嗨,我试图实现一些测试我的jsf应用程序和mocks我使用mockito. (我也用弹簧)
@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()); } }
测试成功,但是当我想使用getInstance方法检索实例时.我之前设置的所有参数(通过之前的构造函数)为null.
我是嘲弄对象的新手,这样的行为是正常的还是我的代码有错误?
解决方法
它实际上取决于GeneralConfigService#getInstance()的实现.如果您使用@InjectMocks注释,还可以简化测试代码.
当使用MockitoJUnitRunner时,您不需要手动初始化mocks并注入依赖项:
@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 ... } }