Skip to content
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

Invariance of MockitoHamcrest#argThat #3155

Open
foaw opened this issue Oct 21, 2023 · 2 comments
Open

Invariance of MockitoHamcrest#argThat #3155

foaw opened this issue Oct 21, 2023 · 2 comments

Comments

@foaw
Copy link

foaw commented Oct 21, 2023

The current signature of MockitoHamcrest#argThat makes it impossible to pass in arguments that are not directly of type T.

@SuppressWarnings("unchecked")
public static <T> T argThat(Matcher<T> matcher) {
reportMatcher(matcher);
return (T) defaultValue(genericTypeOfMatcher(matcher.getClass()));
}

In particular, this means, for example, that one cannot use Matcher<Iterable<T>> in places where Matcher<Collection<T>> is expected, or even the most primitive Matchers.notNullValue(). The only other remedy is to declare a matcher per type, or "monomorphise" it.

This was already brought up some years ago, but then was closed, as MockitoHamcrest was planned for deprecation anyway. After some discussion in #1819, the deprecation commit was reverted in ad2f352. However, the issue remained unaddressed, and so the problem is still there.

@LeMikaelF
Copy link
Contributor

LeMikaelF commented Oct 29, 2023

Here's a possible workaround:

private <T> Matcher<T> adapt(Matcher<? super T> matcher) {
    return new CombinableMatcher<>(matcher);
}

Usage:

class MyClass {
    void doSomething(List<String> list) { }
}
MyClass mock = mock(MyClass.class);
mock.doSomething(List.of("first", "second"));
verify(mock).doSomething(argThat(adapt(hasItems("first"))));

@LeMikaelF
Copy link
Contributor

@foaw This is a problem that I also experience on a regular basis, and I find myself using the above helper method in these situations. However the fix would be really simple, would likely not break any code, and would make using hamcrest matchers a lot easier. I for one would like to see this merged in Mockito (but I'm not a maintainer). Maybe open a PR with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants