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

Mockito silently produces incorrect mocks of jdk classes with java 17 #2561

Closed
montanero opened this issue Feb 9, 2022 · 1 comment
Closed

Comments

@montanero
Copy link

montanero commented Feb 9, 2022

mockito running under java 17 with default settings seems to produce incorrect mocks. What's worse: Mockito produces incorrect mocks silently. The problem can be fixed by invoking java with --add-opens jvm options, but I would expect mockito to fail and in the best case show meaningful text describing the nature of the problem and a possible fix.

  • Code run with java11: works
  • Code run with java 17: fails with NPE (consequence of broken mock)
  • Code run with java 17 --add-opens=java.base/java.io=ALL-UNNAMED: works

Environment

Mockito: 4.3.1
openjdk version "17.0.1" 2021-10-19
OpenJDK Runtime Environment (build 17.0.1+12-Debian-1)
OpenJDK 64-Bit Server VM (build 17.0.1+12-Debian-1, mixed mode, sharing)

Expectations

mockito should either

  • produce correct mocks

OR

  • fail with Exception if correct mocks cannot be produced with the current jvm settings

Code

(complete example here: https://github.com/montanero/mockito-bug.git)

public class TestMockOutputStream {
    @Test
    public void runSpy() throws Exception {
        MyObjectOutputStream original = new MyObjectOutputStream();
        original.writeObject("hello"); // works
        MyObjectOutputStream spied = spy(original);
        spied.writeObject("hello"); // crashes
    }
}

class MyObjectOutputStream extends ObjectOutputStream {
    public MyObjectOutputStream() throws IOException {
        super();
    }
}
@TimvdLippe
Copy link
Contributor

Unfortunately, ObjectOutputStream is one of the classes that Mockito relies on internally for its behavior. Stubbing ObjectOutputStream will therefore lead to undefined behavior. Additionally, it is advised not to mock classes you don't own: https://github.com/mockito/mockito/wiki/How-to-write-good-tests#dont-mock-a-type-you-dont-own We are working on improving the user experience by working on a DoNotMock feature to avoid mocking classes/methods that are known to crash Mockito internals (#1833). Therefore, I am closing this as "Infeasible". Apologies for the uninformative exception that is thrown.

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