2017-08-11 120 views
0

我正在對我的服務之一進行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()」來定義模仿行爲的方式,但仍然無法解決此問題。

我想也許是因爲然後返回()不能返回的東西的集合,但我沒有找到任何資源解釋這一點。如果有人知道一些提示,請讓我知道!非常感謝!

回答

0

我不確定你使用的是什麼版本的java和mockito。 試試這個

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

它的工作原理!你能簡單解釋一下你的版本爲什麼可以工謝謝! –

+0

你正在使用哪個版本的mockito? – want2learn

+0

我相信我在使用1.10.19。 –