How to mock StorageOptions.newBuilder()

95
June 30, 2022, at 07:30 AM

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
Answer 1

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.

Rent Charter Buses Company
READ ALSO
Reduce custom object using RxJava

Reduce custom object using RxJava

I'm using RxJava, I have a list of Point and i want to calculate the distance between each point and get the sum

98
Provide streaming API endpoint as event-stream or ndjson?

Provide streaming API endpoint as event-stream or ndjson?

Spring offers at least 2 possibilities to provide a streaming api response, which are very similar

111
Maximum sum in array given constraints

Maximum sum in array given constraints

Given an array of positive integers, return the maximum sum

88
How can I remove a parameter from a subclass constructor in Java?

How can I remove a parameter from a subclass constructor in Java?

In my superclass, I have defined the parameters a, b, c and dFor its subclass, I want to remove d

77