I try to implement some tests for my JSF application and for the mocks I am using mockito. (I also use spring)
@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 succeeds, but when I want to retrieve the instance with the getInstance
method. All Parameters which I have set before (via the constructor before) are null.
I am new to mocked objects, so is this behavior normal, or is there a mistake in my code?
Advertisement
Answer
It really depends on GeneralConfigService#getInstance() implementation. Also you can simplify your test code a lot if you use @InjectMocks
annotation.
When using MockitoJUnitRunner
you don’t need to initialize mocks and inject your dependencies manually:
@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 ... } }