【问题标题】:Mockito When...thenReturn not returning expected value on CollectionMockito When...thenReturn 不返回 Collection 的预期值
【发布时间】: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:&lt;[]&gt; but was:&lt;[1]&gt;

我很困惑,我不是只是模拟countryToMarketplaceMapper.getMarketplacesForCountries(countries) 的行为来返回一个内部有条目的marketplaces 吗?我做了一些研究,发现了这篇文章:Mockito when/then not returning expected value,我改变了我使用“doReturn()...when()”定义模拟行为的方式,但仍然没有解决这个问题。

我在想也许是因为 thenReturn() 不能返回一个东西的集合,但我没有找到任何解释这一点的资源。如果有人知道一些提示,请告诉我!非常感谢!

【问题讨论】:

    标签: unit-testing mockito


    【解决方案1】:

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

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

    【讨论】:

    • 有效!你能简要解释一下为什么你的版本有效吗?谢谢!
    • 您使用的是哪个版本的 mockito?
    • 我相信我使用的是 1.10.19。
    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多