I have been trying to mock DataManger class in my test classes, but cannot seem to get it working. Any help would be appreciated.
Hello, @doe.john19984!
Could you please provide more information about the way you tried to mock DataManager and what exact problems you have?
Regards,
Dmitry
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@ContextConfiguration(classes = {FerreroTvServiceImpl.class})
@ExtendWith(SpringExtension.class)
class ABCTest {
@Autowired
ApplicationContext applicationContext;
List<ABC> abcListReturnedByDataManager = new ArrayList<>();
@Autowired
private ABC testObj;
@MockBean
private DataManager dataManager;
@MockBean
private ConfigProperties configPropertiesMock;
@Test
void testGetFerreroTvNewAuditelWeeks() {
when(dataManager.load(ABCEntity.class).query(anyString()).list()).thenReturn(abcListReturnedByDataManager);
// assertEquals(1, testObj.getMethod(dummyDownloadDate).size());
// verify(dataManager.load(ABCEntity.class));
}
}
In the above code, Issue appears when the execution reaches when(). dataManager.load() returns null in this instance and thus raises a null pointer exception.
I am new to the Jmix platform so I understand there would be unnecessary and foolish things added in my code. Please help me if there are any better ways of mocking the dataManager.
Hi @taimanov,
This is the way I am trying to mock the DataManager class, and this also explains the issue I am facing.
Thanks in advance for any help.
Hi, John!
In the above example, you are trying to mock the method sequence call.
However, by standard, Mokito is configured to mock only one method.
To add deep mocking capability, you need to add the answer
parameter to the MockBean
annotation.
Ex:
@MockBean(answer = Answers.RETURNS_DEEP_STUBS)
private DataManager dataManager;
And then, you can do deep mocking.
Here is an example for User.class
:
@Test
void test() {
Mockito.when(dataManager.load(User.class).all().list())
.thenReturn(new ArrayList<User>());
Assertions.assertEquals(new ArrayList<User>(), dataManager.load(User.class).all().list());
}
You can read more about deep mocking here.
I hope my answer helps you!
Regards,
Dmitriy