Mockito当...然后返回不返回Collection的预期值

时间:2017-08-11 18:14:32

标签: unit-testing mockito

我正在对我的一项服务进行Mockito单元测试,我试图模仿它,但我无法返回所需的对象。我的代码片段如下所示:

   @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()无法返回一个东西的集合,但我找不到任何解释这个的资源。如果有人知道一些提示,请告诉我!非常感谢!

1 个答案:

答案 0 :(得分:1)

我不确定您使用的是什么版本的java和mockito。 试试这个

Mockito.when(countryToMarketplaceMapper.getMarketplacesForCountries(Mockito.anyListOf(String.class))).thenReturn(marketplaces);