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?
If a method return type is a custom class, a mock returns null because there is no empty value for a custom class. RETURN_MOCKS will try to return mocks if possible instead of null . Since final class cannot be mocked, null is still returned in that case.
thenReturn(null); for (String next = reader. readLine(); next != null; next = reader. readLine()) do something...
Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments.
Following are the differences between thenReturn and doReturn : * Type safety : doReturn takes Object parameter, unlike thenReturn . Hence there is no type check in doReturn at compile time. In the case of thenReturn , whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised.
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 ... } }
My problem here was the incorrect import for Test
anotation:
Was
import org.junit.jupiter.api.Test;
Correct
import org.junit.Test;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With