我有這個問題,我希望我的模擬在某些特定情況下返回特定值,在任何其他情況下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做出這樣的聲明?
在Mockito中,_last定義的匹配規則wins_。這允許在'setUp'和'@ Before'方法中進行一般設置,其中覆蓋特定的'@Test's,但是要求通用規則在特定情況之前(即高於)特定情況。 –