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

MissingMethodInvocationException is thrown when mocking native method in 5.x #3281

Closed
5 tasks done
franzwong opened this issue Feb 29, 2024 · 1 comment · Fixed by #3283
Closed
5 tasks done

MissingMethodInvocationException is thrown when mocking native method in 5.x #3281

franzwong opened this issue Feb 29, 2024 · 1 comment · Fixed by #3283

Comments

@franzwong
Copy link
Contributor

franzwong commented Feb 29, 2024

  • The mockito message in the stacktrace have useful information, but it didn't help
  • The problematic code (if that's possible) is copied here;
    Note that some configuration are impossible to mock via Mockito
  • Provide versions (mockito / jdk / os / any other relevant information)
  • Provide a Short, Self Contained, Correct (Compilable), Example of the issue
    (same as any question on stackoverflow.com)
  • Read the contributing guide

Problematic version: 5.0.0, 5.10.0
JDK: 17
OS: MacOS

The following piece of code was fine with 4.x (I tried with 4.11.0). However, it throws exception after upgrading to 5.x. I think that's because the totalMemory method is native. However, the exception message doesn't mention that.

public class FooTest {
    @Test
    public void fooTest() {
        var runtime = mock(Runtime.class);
        when(runtime.totalMemory()).thenReturn(1000L);
    }
}

Exception message:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.


	at org.example.foo.FooTest.fooTest(FooTest.java:13)
	at java.base/java.lang.reflect.Method.invoke(Method.java:580)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
@TimvdLippe
Copy link
Contributor

A PR that updates the message to list final/private/native/equals()/hashCode() would be welcome!

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

Successfully merging a pull request may close this issue.

2 participants