【发布时间】:2017-08-11 18:14:31
【问题描述】:
我正在对我的一项服务进行 Mockito 单元测试,并尝试对其进行模拟,但我无法返回所需的对象。我的代码的 sn-p 如下所示:
@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);
}
}
现在otherTestInstance.otherMethod("inputString") 通过了测试用例,但countryToMarketplaceMapper.getMarketplacesForCountries(countries) 失败了,因为junit.framework.AssertionFailedError: expected:<[]> but was:<[1]>。
我很困惑,我不是只是模拟countryToMarketplaceMapper.getMarketplacesForCountries(countries) 的行为来返回一个内部有条目的marketplaces 吗?我做了一些研究,发现了这篇文章:Mockito when/then not returning expected value,我改变了我使用“doReturn()...when()”定义模拟行为的方式,但仍然没有解决这个问题。
我在想也许是因为 thenReturn() 不能返回一个东西的集合,但我没有找到任何解释这一点的资源。如果有人知道一些提示,请告诉我!非常感谢!
【问题讨论】:
标签: unit-testing mockito