Springboot+mockito进行单元测试心得整体

简介: ## SpringBoot应用测试 测试Springboot应用需要依赖一个非常重要的注解@SpringBootTest,这个注解会为测试用例构建Spring容器。@SpringBootTest注解修饰的测试用例默认不会启动web容器,如果需要启动web容器需要设置webEnvironment属性: * MOCK(默认):会启动一个mock的web server,可以配合@AutoConfig

SpringBoot应用测试

测试Springboot应用需要依赖一个非常重要的注解@SpringBootTest,这个注解会为测试用例构建Spring容器。@SpringBootTest注解修饰的测试用例默认不会启动web容器,如果需要启动web容器需要设置webEnvironment属性:

  • MOCK(默认):会启动一个mock的web server,可以配合@AutoConfigureMockMvc注解对web应用进行测试(后面会举例)
  • RANDOM_PORT:创建ApplicationContext上下文,启动一个真实的Web容器,监听一个随机的端口。
  • DEFINED_PORT:创建ApplicationContext上下文,启动一个真实的Web容器,监听SpringBoot配置配置文件中指定的端口,默认是8080端口。
  • NONE:只是启动ApplicationContext,不会启动任何(Mock或者非Mock)web容器。

如果是使用Junit来进行单元测试,再增加一个@RunWith(SpringRunner.class)或者@RunWith(SpringJUnit4ClassRunner.class)注解。

利用模拟Web容器来测试Restful接口

当测试用例使用@SpringBootTest注解修饰并将webEnvironment属性设置MOCK之后,测试用例在执行的过程中,就会创建一个模拟的web容器。为了让测试用例能够访问这个模拟的web容器,还需要增加@AutoConfigureMockMvc注解,这样就可以把MockMvc对象利用@Autowired注解注入到测试用例的属性中。MockMvc类的作用就是可以访问模拟的Web容器。接下来我们看一下使用MockMvc配合MockMvcRequestBuilders及MockMvcResultMatchers来访问模拟的Web容器进行测试Rest接口的例子:

  • GET请求
    @Test
    public void testCase() throws Exception {
        MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/testQueryData.json?id=6"))
                .andExpect(
                        MockMvcResultMatchers.status().isOk()).andReturn();
       Assert.assertNotNull(result.getResponse().getContentAsString());
    }
  • POST请求提交表单
    @Test
    public void testCase() throws Exception {
        UrlEncodedFormEntity formData = new UrlEncodedFormEntity(Arrays.asList(
                new BasicNameValuePair("param1", "xxxxxxx"),
                new BasicNameValuePair("param2", "xxxxxxx")
        ), "utf-8");
        MvcResult result = mvc.perform(MockMvcRequestBuilders.post("/testPostData.json")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
          .content(EntityUtils.toString(formData))).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
        Assert.assertNotNull(result.getResponse().getContentAsString());
    }
  • DELETE请求
    @Test
    public void testCase() throws Exception {
        mvc.perform(MockMvcRequestBuilders.delete("/testDeleteData.json?id=1"))
                .andExpect(
                        MockMvcResultMatchers.status().isOk());
    }
  • PUT请求类似POST
    @Test
    public void testCase() throws Exception {
        MvcResult result = mvc.perform(MockMvcRequestBuilders.put("/testPutData"))
                .andExpect(
                        MockMvcResultMatchers.status().isOk()).andReturn();
        Assert.assertNotNull(result.getResponse().getContentAsString());
    }

利用TestRestTemplate测试真实的Restful接口

Springboot提供了专门用来测试Restful接口的工具类TestRestTemplate,这个类对RestTemplate进行了封装,可以让用户很快捷的编写出http客户端测试代码。
实例如下:

  • GET请求
public void testCase() throws Exception {
  String restUrl = "http://localhost:8080/xxxxx/xxxxx.json?id=xxx";
  ResponseEntity<RegcoreResp> response = testRestTemplate.getForEntity(restUrl, RegcoreResp.class);    //RegcoreResp是用户自行定义的返回的数据封装Bean,
  System.out.println(response.getBody());
}
  • POST请求并采用表单方式提交数据
public void testCase() throws Exception {
String restUrl = "http://localhost:8080/xxxxx/xxxxx.json";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("name", "testName"); 
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        ResponseEntity<RegcoreResp> response = testRestTemplate.postForEntity(restUrl, requestEntity, RegcoreResp.class);
}
  • POST请求并采用request Body方式传输数据
public void testCase() throws Exception {
        String restUrl = "http://localhost:8080/xxxxx/xxxxx.json";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String body = "{\"id\":\"xxxxxx\",\"status\":\"xxxxx\"}";
        HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
        ResponseEntity<BaseFacadeResp> response = testRestTemplate.postForEntity(restUrl, requestEntity, BaseFacadeResp.class);
}
  • DELETE
public void testCase() throws Exception {
        String restUrl = "http://localhost:8080/xxxxx/xxxxx.json";
        testRestTemplate.delete(restUrl);  //delete方法没有返回值
}
  • PUT方式与POST类似
public void testCase() throws Exception {
        String restUrl = "http://localhost:8080/xxxxx/xxxxx.json";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String body = "{\"id\":\"xxxxxx\",\"status\":\"xxxxx\"}";
        HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
        testRestTemplate.put(restUrl, requestEntity);  //put方法没有返回值
}

Mock与Spy

  • Mock利用动态代理对一个接口或者类的所有方法进行模拟。
  • Spy同样利用动态代理,与Mock不同的是Spy针对于一个真实对象进行模拟并可以对被监控对象中某个方法进行打桩(stubed)控制该方法的执行情况,其他没有打桩的方法则按照对象本身的实际逻辑执行。

SpringBoot对Mock Spy的支持

在测试SpringBoot应用过程中,某些环境依赖问题可能导致无法调用真实Bean逻辑,比如:某些外部依赖的接口没有准备好。这个时候需要使用Mock、Spy来对Bean进行模拟。SpringBoot提供了@MockBean和@SpyBean两个注解来实现Mock与Spy能力。由于底层还是使用Mockito,用法上与Mockito没有区别。
示例:

@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");
  }
}

如何Mock方法模拟内部逻辑?

一般来说mock最典型的用法就是对一个方法的返回值(输出)进行模拟。如果想模拟方法内部逻辑,比如方法对入参进行修改或者对入参对象的某个方法进行回调如何利用mock来实现呢?
下面举一个实际的场景,比如有这样一段被测试代码:

  testDOMapper.insert(testBeanDO);
  if(testBeanDO.getId()==null) {
       throw new RuntimeException();
  }

插入数据之后数据库中新纪录的id会回填到templateDO.id这个属性,这个特性是mybatis的一种常用的用法。但是如果我们用Mock如果来实现测试代码执行过testDOMapper.insert(templateDO)之后将templateDO.id属性附上值,如何实现呢?这里要用Answer这个接口

       Mockito.when(testDOMapper.insert(Mockito.any(TestBeanDO.class))).thenAnswer(new 
          Answer<Integer>() {
            @Override
            public Integer answer(InvocationOnMock invocation) throws Throwable {
                TestBeanDO arg = invocation.getArgumentAt(0, TestBeanDO.class);
                arg.setId(1L);
                return 1;
            }
        });

上面的代码可以看到answer可以模拟调用insert()方法时方法体如何执行。answer的入参InvocationOnMock对象可以获取实际的入参的对象,这样只要在answer方法体里对入参属性进行修改就可以实现我们想要达到的效果了。
类似的方法还可以使用 ArgumentMatcher 来实现对参数进行捕获修改,这里给出示例就不再具体说明了。

        Mockito.when(testDOMapper.insert(Mockito.argThat(new ArgumentMatcher<TestBeanDO>() {
            @Override
            public boolean matches(Object argument) {
                ((TestBeanDO) argument).setId(1L);
                return true;
            }
        }))).thenReturn(1);

给Spy的对象进行打桩

spy一般对监控一个真实的对象,按照之前mock的常见用法:

Mockito.when(spyObj.method()).thenReturn(xxxx);  

其实是不会按照thenReturn()指定的结果返回的,这一点要特别的注意,容易采坑。如果想按照用户自己的定义对spy对象进行打桩的正确方式是:

Mockito.doReturn(xxxx).when(sypObj).method();

提前设置好方法被调用之后的表现doReturn()返回结果还是doThrow()抛出异常,之后再使用when(spyObj)对spy的对象进行包装之后设置调用的方法就可以了。

相关文章
|
4月前
|
Java 测试技术 数据库
如何做SpringBoot单元测试?
如何做SpringBoot单元测试?
|
4月前
|
XML SQL Java
ClickHouse【SpringBoot集成】clickhouse+mybatis-plus配置及使用问题说明(含建表语句、demo源码、测试说明)
ClickHouse【SpringBoot集成】clickhouse+mybatis-plus配置及使用问题说明(含建表语句、demo源码、测试说明)
140 0
|
8天前
|
Java 测试技术
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
14 0
|
1月前
|
Java 测试技术 数据库
springboot大学生体质测试管理系统
springboot大学生体质测试管理系统
|
3月前
|
Java 测试技术
SpringBoot整合Junit进行单元测试
SpringBoot整合Junit进行单元测试
29 0
|
3月前
|
监控 Java 测试技术
基于springboot实现的个人性格测试系统(分前后端)
基于springboot实现的个人性格测试系统(分前后端)
|
3月前
|
前端开发 Java 测试技术
SpringBoot - 应用程序测试方案
SpringBoot - 应用程序测试方案
50 0
|
4月前
|
Java Linux 开发工具
MinIO【部署 01】MinIO安装及SpringBoot集成简单测试
MinIO【部署 01】MinIO安装及SpringBoot集成简单测试
122 0
|
4月前
|
监控 Java
Pinpoint【部署 02】Pinpoint Agent 安装启动及监控 SpringBoot 项目案例分享(添加快速测试math-game.jar包)
Pinpoint【部署 02】Pinpoint Agent 安装启动及监控 SpringBoot 项目案例分享(添加快速测试math-game.jar包)
66 0
|
4月前
|
NoSQL Java API
SpringBoot【ElasticSearch集成 02】Java HTTP Rest client for ElasticSearch Jest 客户端集成(依赖+配置+增删改查测试源码)推荐使用
SpringBoot【ElasticSearch集成 02】Java HTTP Rest client for ElasticSearch Jest 客户端集成(依赖+配置+增删改查测试源码)推荐使用
54 0