如何模拟 StorageOptions.newBuilder()

How to mock StorageOptions.newBuilder()

你能帮我模拟一下吗StorageOptions.newBuilder()

要模拟的代码:

StorageOptions.newBuilder.setProjectId("Test").build().getService()

我写的代码:

Storage mockStorage = Mockito.mock(Storage.class);

MockedStatic<StorageOptions> storageOptionsMock = Mockito.mockStorage(StorageOptions.class);
storageOptionsMock.when( ()-> StorageOptions.newBuilder().setProjectId("Test").build().getService()).thenReturn(mockStorage);

错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Storage$MockitoMock39527098 cannot be returned by newBuilder()
newBuilder() should return Builder

因为你链接了很多方法调用,你可以使用 Mockito.RETURNS_DEEP_STUBS 来指示 Mockito return 所有需要的中间体 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);

但由于这被认为是 anti pattern,您可能需要重构代码以避免这种情况。