UNIQUEorn
UNIQUEorn

Reputation: 418

Injecting mocks with @Mock does not work with Java 13

I'm currently trying to migrate a project to Java 13 (inclusive module-info.java which is important for the problem), JUnit 5, the latest Mockito version 3.3.3 and Maven.

But apparently injecting mocks using @Mock does not work, when I run the tests with Maven.

I tried to create a mock-instance from an interface. My test looks like this:

@ExtendWith(MockitoExtension.class)
public class MockitoTest {
    @Mock
    protected MyInterface myMock;
    @Test
    public void shouldMock() {
      // Do something
    }
}

The error is the following:

[INFO] Running com.github.schuettec.mocktest.MockitoTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.416 s <<< FAILURE! - in com.github.schuettec.mocktest.MockitoTest
[ERROR] com.github.schuettec.mocktest.MockitoTest.shouldMock Time elapsed: 0.401 s  <<< ERROR!
org.mockito.exceptions.base.MockitoException: Problems setting field myMock annotated with @org.mockito.Mock(name="", stubOnly=false, extraInterfaces={}, answer=RETURNS_DEFAULTS, serializable=false, lenient=false)
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field protected com.github.schuettec.mocktest.MyInterface  com.github.schuettec.mocktest.MockitoTest.myMock accessible: module mocktest does not "opens com.github.schuettec.mocktest" to unnamed module @6b9ce1bf

[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Errors: 
[ERROR]   MockitoTest.shouldMockBothWithoutOpens » Mockito Problems setting field innerM...
[INFO] 
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

I'm running on JDK 13 so I added a module-info.java. It's very simple:

module mocktest {
    exports com.github.schuettec.mocktest;
}

When I add open module the test works fine. But I don't want to declare my module open for reflection.

Am I missing something?

If you want to have a look, I uploaded a minimum example: https://github.com/schuettec/junit5-java13-test

And the build log is here: https://travis-ci.org/github/schuettec/junit5-java13-test/builds/683407777

Upvotes: 1

Views: 1338

Answers (0)

Related Questions