I'm doing a Mockito unit test on one of my service and I tried to mock it, but I cannot return the desired object. A snippet of my code looks like this:
@RunWith(MockitoJUnitRunner.class)
public class RunBinaryApprovalActivityTest {
@Mock
CountryToMarketplaceMapper countryToMarketplaceMapper;
@Test
void doSomeTestHere() {
Set<Integer> marketplaces = new HashSet<Integer>();
marketplaces.add(1);
List<String> countries = new ArrayList<String>();
countries.add("US");
Mockito.when(countryToMarketplaceMapper.getMarketplacesForCountries(Mockito.anyCollection())).thenReturn(marketplaces);
Mockito.when(otherTestInstance.otherMethod("inputString")).thenReturn("ExpectedOutput");
Assert.assertEquals(otherTestInstance.otherMethod("inputString"),"ExpectedOutput");
Assert.assertEquals(countryToMarketplaceMapper.getMarketplacesForCountries(countries), marketplaces);
}
}
Right now the otherTestInstance.otherMethod("inputString")
passed the test case but the countryToMarketplaceMapper.getMarketplacesForCountries(countries)
failed because junit.framework.AssertionFailedError: expected:<[]> but was:<[1]>
.
I'm confused, didn't I just simulate the behavior of countryToMarketplaceMapper.getMarketplacesForCountries(countries)
to return a marketplaces
which has entry inside? I did some research and found this post: Mockito when/then not returning expected value and I chenged how I defined the mocking behaviour using "doReturn()...when()" but still doesn't resolve this issue.
I'm thinking maybe it's because thenReturn() cannot return a collection of thing but I didn't find any resource that explain this. If anyone know some hint, please let me know! Lots of thanks!