Reputation: 9934
Is there a way with Mockito to verify that a method is called with a parameter that within a closed set. For example, can I assert that a method
void addToNotWorthyList(String guitaristName);
is called with guitaristName is within the set ("Jeff Beck", "Seasick Steve", "Steve Howe")?
Upvotes: 0
Views: 377
Reputation: 95654
verify(systemUnderTest).addToNotWorthyList(argThat(isOneOf(
"Jeff Beck", "SeasickSteve", "Steve Howe")));
This uses Hamcrest's isOneOf
, which is available in 1.3 at least. If you already have the items in a collection or array, skip directly to isIn
.
verify(systemUnderTest).addToNotWorthyList(argThat(isIn(setOfNames)));
Upvotes: 5
Reputation: 15518
You can do it with at least answers and 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));
}
}
}
Upvotes: 1
Reputation: 9934
FWIW.. Here is what i came up with
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);
}
}
And then I use the
Mockito.argThat(new SetMatcher<String>(Arrays.asList(new String[] { "Jeff Beck", "Seasick Steve", "Steve Howe" } )));
Upvotes: 0