2014-03-12 32 views
0

我有這個問題,我希望我的模擬在某些特定情況下返回特定值,在任何其他情況下anyString()在下面的代碼中。在規則中使用Mockito的anyString()不適用於其他規則中的「正常」值

@Test 
public void testMockitoWithAny() { 
    // Mock the object 
    List<String> list = mock(List.class); 

    // populate the mock with the rules 
    when(list.add("abc")).thenReturn(false);  // first rule 
    when(list.add(anyString())).thenReturn(true); // default rule 

    // Verify the rules. 
    assertTrue(list.add("xyz"));     // Ok 
    assertFalse(list.add("abc"));     // AssertionError. 
} 

如何用Mockito做出這樣的聲明?

回答

1

好吧,我找到了答案。我只需要切換規則先設置默認的規則。

@Test 
public void testMockitoWithAny() { 
    // Mock the object 
    List<String> list = mock(List.class); 

    // populate the mock with the rules 
    when(list.add(anyString())).thenReturn(true); // default rule 
    when(list.add("abc")).thenReturn(false);  // first rule 

    // Verify the rules. 
    assertTrue(list.add("xyz"));     // Ok 
    assertFalse(list.add("abc"));     // Ok 
} 
+1

在Mockito中,_last定義的匹配規則wins_。這允許在'setUp'和'@ Before'方法中進行一般設置,其中覆蓋特定的'@Test's,但是要求通用規則在特定情況之前(即高於)特定情況。 –

0

你需要它匹配任何字符串除了 「abc」 一個匹配:

import static org.hamcrest.CoreMatchers.*; 
... 

when(list.add(argThat(not(equalTo("abc"))))).thenReturn(true); // default rule 
+0

爲什麼我一直在做SSCCE?我的一半簡化問題得到的答案不符合我的實際情況。在這個實際案例中,我有一個完整的字符串列表,它提供了幾個不同的(mockito)答案。我真的不得不重複所有那些,我想,'argThat(not(in(Arrays.asList(「abc」,「def」,「ghi」))))'? Mockito中沒有更聰明的東西嗎? –

+0

我不知道有這樣的事情。但是這看起來像是一個測試,做了太多事情。難道你不能在簡單的測試中分割它嗎? –

+0

嗯,有時我必須在200行方法中模擬幾個非常具體的東西,而且我沒有時間重構,因此在我的情況下不幸的是您的建議不可用。不管怎麼說,多謝拉! :) –