有没有办法用 Mockito 验证一个方法是否被调用了一个闭合集合中的参数。例如,我可以断言一个方法
void addToNotWorthyList(String guitaristName);
被称为吉他手名称在集合内("杰夫贝克","晕船史蒂夫","史蒂夫豪")?
verify(systemUnderTest).addToNotWorthyList(argThat(isOneOf(
"Jeff Beck", "SeasickSteve", "Steve Howe")));
这使用哈姆克雷斯特的isOneOf
,至少在1.3中可用。如果集合或数组中已有项目,请直接跳到isIn
。
verify(systemUnderTest).addToNotWorthyList(argThat(isIn(setOfNames)));
你至少可以用答案和论证俘虏来做到这一点。
public class MyTest {
class Idols {
void addToNotWorthyList(String guitaristName) {
//testing purposes
}
}
private List<String> expectedValues = new ArrayList() {{
add("Jeff Beck");
add("Seasick Steve");
add("Steve Howe");
}};
@Mock
private Idols mock;
@Before
public void setup() {
initMocks(this);
}
@Test
public void checkWithAnswer() {
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String actualGuitarist = (String) invocation.getArguments()[0];
assertTrue("Found unexpected guitarist [" + actualGuitarist + "]", expectedValues.contains(actualGuitarist));
return null;
}
}).when(mock).addToNotWorthyList(anyString());
mock.addToNotWorthyList("Jeff Beck");
mock.addToNotWorthyList("Jeff");
verify(mock, atLeast(0)).addToNotWorthyList(anyString());
}
@Test
public void checkWithArgumentCaptor() {
ArgumentCaptor<String> usedGuitarists = ArgumentCaptor.forClass(String.class);
mock.addToNotWorthyList("Jeff Beck");
mock.addToNotWorthyList("Jeff");
verify(mock, atLeast(0)).addToNotWorthyList(usedGuitarists.capture());
for (String actualGuitarist : usedGuitarists.getAllValues()) {
assertTrue("Found unexpected guitarist [" + actualGuitarist + "]", expectedValues.contains(actualGuitarist));
}
}
}
FWIW..这是我想到的
public class SetMatcher<T> extends ArgumentMatcher<T> {
private final Set<T> set;
public MockitoSetMatcher(List<T> list) {
set = new HashSet<T>(list);
}
@Override
public boolean matches(Object argument) {
return set.contains(argument);
}
}
然后我使用
Mockito.argThat(new SetMatcher<String>(Arrays.asList(new String[] { "Jeff Beck", "Seasick Steve", "Steve Howe" } )));