Skip to content

Commit

Permalink
Add ArgumentMatchers#assertArg method.
Browse files Browse the repository at this point in the history
  • Loading branch information
maciejwalkowiak committed Mar 25, 2023
1 parent 5486617 commit 1d1d293
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/main/java/org/mockito/ArgumentMatchers.java
Expand Up @@ -14,6 +14,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.regex.Pattern;

import org.mockito.internal.matchers.Any;
Expand Down Expand Up @@ -912,6 +913,21 @@ public static <T> T argThat(ArgumentMatcher<T> matcher) {
return null;
}

/**
* Allows creating custom argument matchers where matching is considered successful when the consumer given by parameter does not throw an exception.
* <p>
* Typically used with {@link Mockito#verify(Object)} to execute assertions on parameters passed to the verified method invocation.
*
* @param consumer executes assertions on the verified argument
* @return <code>null</code>.
*/
public static <T> T assertArg(Consumer<T> consumer) {
return argThat(argument -> {
consumer.accept(argument);
return true;
});
}

/**
* Allows creating custom <code>char</code> argument matchers.
* <p>
Expand Down
24 changes: 24 additions & 0 deletions src/test/java/org/mockitousage/matchers/MatchersTest.java
Expand Up @@ -52,6 +52,7 @@
import java.util.RandomAccess;
import java.util.regex.Pattern;

import org.junit.ComparisonFailure;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
Expand Down Expand Up @@ -624,4 +625,27 @@ public void nullable_matcher() throws Exception {

verify(mock, times(2)).oneArg(nullable(Character.class));
}

@Test
public void assertArg_matcher() throws Exception {
mock.oneArg("hello");

verify(mock).oneArg(Mockito.assertArg((String it) -> {
assertEquals("hello", it);
}));
}

@Test
public void assertArg_matcher_fails_when_assertion_fails() throws Exception {
mock.oneArg("hello");

try {
verify(mock).oneArg(Mockito.assertArg((String it) -> {
assertEquals("not-hello", it);
}));
fail("Should throw an exception");
} catch (ComparisonFailure e) {
// do nothing
}
}
}

0 comments on commit 1d1d293

Please sign in to comment.