Reputation: 746
I'm migrating from PowerMockito&MockitoV2 to Mockito V3+ and trying to rewrite my tests
Previously I had a test which mocker java.sql.DriverManager class static method getConnection(...) to return a plain Mockito.mock(java.sql.Connection.class), now I'm trying to do somethins similar with MockedStatic but can't make static mock return another plain mock, have such error:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue: Connection$MockitoMock$sLucRb7f cannot be returned by getConnection() getConnection() should return Connection *** If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because:
- This exception might occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing.
- A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
My test code looks like that:
@Test
public void testConnectionIsOk() {
Connection mockedConnection = Mockito.mock(Connection.class);
try (MockedStatic<DriverManager> driverManagerMockedStatic = Mockito.mockStatic(DriverManager.class)) {
driverManagerMockedStatic.when(
() -> DriverManager.getConnection(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
.thenReturn(mockedConnection);
boolean isConnectionOK = sut.testMethod();
Assertions.assertTrue(isConnectionOK);
}
}
I understand the error is asking me to use a Mockito.doReturn(mockedConnection).when(...)
but I can't pass a static method call in that .when(...)
block
Is there any workaround for this use case or am I missing anything?
Upvotes: 3
Views: 598
Reputation: 1069
You can use thenAnswer
instead of thenReturn
and just return lambda expression like:
@Test
public void testConnectionIsOk() {
Connection mockedConnection = Mockito.mock(Connection.class);
try (MockedStatic<DriverManager> driverManagerMockedStatic = Mockito.mockStatic(DriverManager.class)) {
driverManagerMockedStatic.when(() -> DriverManager.getConnection(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
.thenAnswer(invocation -> mockedConnection);
boolean isConnectionOK = sut.testMethod();
Assertions.assertTrue(isConnectionOK);
}
}
Upvotes: 2