Issue
Can you help me in mocking StorageOptions.newBuilder()
Code to be Mocked:
StorageOptions.newBuilder.setProjectId("Test").build().getService()
Code I have written:
Storage mockStorage = Mockito.mock(Storage.class);
MockedStatic<StorageOptions> storageOptionsMock = Mockito.mockStorage(StorageOptions.class);
storageOptionsMock.when( ()-> StorageOptions.newBuilder().setProjectId("Test").build().getService()).thenReturn(mockStorage);
Error:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Storage$MockitoMock$1939527098 cannot be returned by newBuilder()
newBuilder() should return Builder
Solution
Since you are chaining a lot of method calls, you can use Mockito.RETURNS_DEEP_STUBS
to instruct Mockito to return all the required intermediate stubs/mocks.
Storage mockStorage = Mockito.mock(Storage.class);
MockedStatic<StorageOptions> storageOptionsMock =
Mockito.mockStatic(StorageOptions.class, Mockito.RETURNS_DEEP_STUBS);
storageOptionsMock.when(()->
StorageOptions.newBuilder()
.setProjectId("Test")
.build()
.getService())
.thenReturn(mockStorage);
assertThat(StorageOptions.newBuilder()
.setProjectId("Test")
.build()
.getService())
.isEqualTo(mockStorage);
But since this is considered an anti pattern, you may want to refactor your code to avoid this.
Answered By - gere
Answer Checked By - David Goodson (JavaFixing Volunteer)