Skip to content

Commit

Permalink
Fixes mockito#2285 : 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 f7b55d1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
17 changes: 17 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,22 @@ 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
21 changes: 21 additions & 0 deletions src/test/java/org/mockitousage/matchers/MatchersTest.java
Expand Up @@ -20,6 +20,7 @@
import static org.mockito.AdditionalMatchers.lt;
import static org.mockito.AdditionalMatchers.not;
import static org.mockito.AdditionalMatchers.or;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.any;
Expand Down Expand Up @@ -52,6 +53,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 +626,23 @@ 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(assertArg((String it) -> assertEquals("hello", it)));
}

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

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

0 comments on commit f7b55d1

Please sign in to comment.