1

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

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
UNIQUEorn
  • 420
  • 6
  • 17
  • look for `-add-opens` โ€“ Naman May 05 '20 at 16:26
  • I could add the argument but then I will have to do this for IDE and Maven separately and for every test case I want to launch in eclipse for example. Seems not suitable. The Mockito documentation also says nothing about add-opens arg to be required. โ€“ UNIQUEorn May 05 '20 at 16:45
  • Have you tried calling [`initMocks()`](https://stackoverflow.com/a/40962941/7859515)? โ€“ MyStackRunnethOver Sep 15 '20 at 22:56

0 Answers0