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

ArgumentMatchers not working for Mockito.mockStatic #2497

Closed
nicolasmafra opened this issue Dec 6, 2021 · 4 comments
Closed

ArgumentMatchers not working for Mockito.mockStatic #2497

nicolasmafra opened this issue Dec 6, 2021 · 4 comments

Comments

@nicolasmafra
Copy link

When I do a mockStatic with argument matchers like this:

var mockedRequestClass = Mockito.mockStatic(RequestClass.class);
mockedRequestClass.when(() -> RequestClass.sendRequest(mockedUrl, any(), any())).thenReturn(null);

Mockito throws the following exception:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'.

How can I use argument matchers with Mockito.mockStatic? Shouldn't that be possible?

@nicolasmafra
Copy link
Author

Note: if I remove ArgumentMatchers no exceptions are thrown.

@nicolasmafra nicolasmafra changed the title ArgumentMatchers not work for Mockito.mockStatic ArgumentMatchers not working for Mockito.mockStatic Dec 6, 2021
@Cybermite
Copy link

Cybermite commented Dec 10, 2021

@nickmafra try using matchers for all the params (see the added eq matcher below):

var mockedRequestClass = Mockito.mockStatic(RequestClass.class);
mockedRequestClass.when(() -> RequestClass.sendRequest(eq(mockedUrl), any(), any())).thenReturn(null);

When using traditional mocks, it'll tell you to use matchers for all the params when at least one of them uses a matcher. My hunch is it's the same for MockedStatic and the exception you're getting is misleading because it swallowed the root cause of the issue.

@TimvdLippe
Copy link
Contributor

Sounds like we should update mockStatic to behave similar to the others, where we validate the argument matchers. PRs welcome!

@temp-droid
Copy link
Contributor

Hi @TimvdLippe , I think the issue comes from here:
https://github.com/mockito/mockito/blob/main/src/main/java/org/mockito/internal/MockedStaticImpl.java#L48-L60

The validation is happening but ignored. Not sure why, but this could fix it if we want to keep the catch Throwable for backwards compatibility:

        try {
            verification.apply();
        } catch (MockitoException exception) {
            throw exception;
        } catch (Throwable ignored) {
        }

What do you think?

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

No branches or pull requests

4 participants