Mockito 有没有办法验证是否使用封闭集中的参数调用方法。例如,我可以断言一个方法
void addToNotWorthyList(String guitaristName);
被称为与 guitaristName 在集合内(“Jeff Beck”、“Seasick Steve”、“Steve Howe”)?
Mockito 有没有办法验证是否使用封闭集中的参数调用方法。例如,我可以断言一个方法
void addToNotWorthyList(String guitaristName);
被称为与 guitaristName 在集合内(“Jeff Beck”、“Seasick Steve”、“Steve Howe”)?
您至少可以使用answers和argument captors来做到这一点。
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" } )));