繁体   English   中英

Mockito:如何模拟 spring 注入的 object 没有无参数构造函数的特殊 DI

[英]Mockito: How to mock spring special DI that the injected object doesn't have no-arg constructor

我在单元测试中使用Mockito 3.4.6 ,实际上,我已经将 Mockito 集成到我的单元测试中并且运行良好。 虽然,现在我需要优化一些单元测试,这是一个特殊的依赖注入,注入的 object没有无参数构造函数,我试过@Spy但它没有用。

我的测试:我试过 1. @Spy 2. @Spy设置实例 using = getDtInsightApi() ; 3. @Spy@InjectMocks ,所有测试都失败了。 正如 Mockito 文档所说,它似乎不适用于这种情况。

@InjectMocks Mockito 将尝试仅通过构造函数注入、setter 注入或属性注入来注入模拟,如下所述。

此外,如果仅使用@Spy ,它将抛出MockitoException

org.mockito.exceptions.base.MockitoException: 
Failed to release mocks

This should not happen unless you are using a third-part mock maker

...
Caused by: org.mockito.exceptions.base.MockitoException: Unable to initialize @Spy annotated field 'api'.
Please ensure that the type 'DtInsightApi' has a no-arg constructor.
...
Caused by: org.mockito.exceptions.base.MockitoException: Please ensure that the type 'DtInsightApi' has a no-arg constructor.

请参阅我的伪代码如下

配置 class:

@Configuration
public class SdkConfig {

    @Resource
    private EnvironmentContext environmentContext;

    @Bean(name = "api")
    public DtInsightApi getApi() {
     
        DtInsightApi.ApiBuilder builder = new DtInsightApi.ApiBuilder()
                    .setServerUrls("sdkUrls")
        return builder.buildApi();
    }
}

DtInsightApi class没有公共无参数构造函数并通过其内部 class 获取实例

public class DtInsightApi {
    private String[] serverUrls;

    DtInsightApi(String[] serverUrls) {
        this.serverUrls = serverUrls;
    }
    
    // inner class
    public static class ApiBuilder {
        String[] serverUrls;

        public ApiBuilder() {
        }
        ...code...

        public DtInsightApi buildApi() {
           return new DtInsightApi(this.serverUrls);
        }
    }

    ...code...

}

单元测试 class:

public Test{
   
   @Autowired
   private PendingTestService service;

   @Spy
   private Api api = getDtInsightApi();

   @Mock
   private MockService mockService;

   @Before
    public void setUp() throws Exception {
        // open mock
        MockitoAnnotations.openMocks(this);
        // i use doReturn(...).when() for @Spy object
        Mockito.doReturn(mockService).when(api)
                   .getSlbApiClient(MockService.class);
        Mockito.when(mockService.addOrUpdate(any(MockDTO.class)))
                   .thenReturn(BaseObject.getApiResponseWithSuccess());
    }

    public DtInsightApi getDtInsightApi () {
        return new DtInsightApi.ApiBuilder()
                .setServerUrls(new String[]{"localhost:8080"})
                .buildApi();
    }

    @Test
    public void testUpdate() {
        service.update();
    }
}

PendingTestService

@Service
public class PendingTestService{
   
   @Autowired
   DtInsightApi api;

   public void update() {
      // here mockService isn't the object i mocked
      MockService mockService = api.getSlbApiClient(MockService.class);
      mockService.update();
   }
}

问题:如何模拟没有无参数构造函数的 DI object DtInsightApi。

在检查了 Spring 有关单元测试的文档后,我找到了使用@MockBean的解决方案。

Spirng 文档: https://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/html/boot-features-testing.html

根据 Spring 文档,您可以使用@MockBeanApplicationContext中模拟一个 bean ,因此我可以使用@MockBean来模拟DtInsightApi

在运行测试时,有时需要在应用程序上下文中模拟某些组件。 例如,您可能拥有一些在开发期间不可用的远程服务的外观。 当您想要模拟在真实环境中可能难以触发的故障时,Mocking 也很有用。

Spring Boot 包含一个@MockBean注释,可用于为ApplicationContext中的 bean 定义 Mockito 模拟。 您可以使用注解添加新的 bean,或替换单个现有的 bean 定义。 注释可以直接用于测试类、测试中的字段或@Configuration类和字段。 当在一个字段上使用时,创建的 mock 的实例也将被注入。 模拟 bean 在每个测试方法后自动重置。

我的解决方案:使用@MockBeanBDDMockito.given(...).willReturn(...) ,使用@Qualifier("api")指定 bean 名称,因为@MockBean由 class 类型注入,如果你有相同的 class beans ,您需要指定 bean 名称。

我在测试 class 中的代码:

public class Test{
    @MockBean
    @Qualifier("api")
    private DtInsightApi api;

   @Mock
   private MockService mockService;

    @Before
    public void setUp() throws Exception {
        // open mock
        MockitoAnnotations.openMocks(this);
        BDDMockito.given(this.api.getSlbApiClient(MockService.class)).willReturn(mockService);
    }

    @Autowired
    private PendingTestService service;


    @Test
    public void testUpdate() {
        service.update();
    }
}

调试 mockService 可以看到 mockService 实例是由Mockito生成的,mock 成功。

也可以参考Spring docs example: mock RemoteService in unit test。

import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.context.*;
import org.springframework.boot.test.mock.mockito.*;
import org.springframework.test.context.junit4.*;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {

    @MockBean
    private RemoteService remoteService;

    @Autowired
    private Reverser reverser;

    @Test
    public void exampleTest() {
        // RemoteService has been injected into the reverser bean
        given(this.remoteService.someCall()).willReturn("mock");
        String reverse = reverser.reverseSomeCall();
        assertThat(reverse).isEqualTo("kcom");
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM