New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ArgumentMatcher like assertArg() for multiple different calls? #3307
Comments
In the code above, the 'someMock.someMethod' function is called twice with different arguments.
In the above code, assert false is thrown in assertThat() when called with '2' entered as the first parameter. I think it's a question of usage. |
There is one way but it is not very elegant, so just treat it as a fun fact 🙂 You can make some static utility method similar to public static <T> T assertArgs(Consumer<T>... assertions) {
AtomicInteger counter = new AtomicInteger();
return ArgumentMatchers.argThat(actual -> {
int index = counter.getAndIncrement();
if (assertions.length > index) {
assertions[index].accept(actual);
}
return true;
});
} Then in your test you can write: @Test
void verifyTwoDifferentCallsWithAssertArgs() {
someMock.someMethod(1, "any string");
someMock.someMethod(2, "any string");
verify(someMock, times(2)).someMethod(
assertArgs(
firstInt -> assertThat(firstInt).isEqualTo(1),
secondInt -> assertThat(secondInt).isEqualTo(2)),
anyString());
} There is probably one more better way to do it, but I didn't check it yet: you could try to handle you assertion in |
Expected behaviour should be consistent with the other argument matchers. In the simplest case that means it should not fail if there is at least a single matching verification. In @Test
void assertArgShouldNotFailExample() {
Consumer<Integer> mock = mock();
mock.accept(1);
mock.accept(2);
verify(mock).accept(assertArg(i -> assertThat(i).isEqualTo(2)));
} Because the below two examples do not fail either: @Test
void verifyExampleA() {
Consumer<Integer> mock = mock();
mock.accept(1);
mock.accept(2);
verify(mock).accept(argThat(i -> i == 2));
} @Test
void verifyExampleB() {
Consumer<Integer> mock = mock();
mock.accept(1);
mock.accept(2);
verify(mock).accept(eq(2));
} |
Discussed in #3170
Originally posted by jpgoelz November 8, 2023
When verifying multiple different calls to a method of a mock, it is possible to call
verify()
twice for each invocation.This will work when not using matchers:
This will also work when using simple matchers:
However, it does not work when using
assertArg()
:The reason behind this is probably the inner assertion failing on at least one of the calls.
So far, the only way I know how to test something like this is to use ArgumentCaptors:
Now, my question: Is there any way to do this without using an ArgumentCaptor?
The text was updated successfully, but these errors were encountered: