SpirngBoot测试

简介: SpirngBoot测试

一、依赖

<spring-boot.version>2.4.2</spring-boot.version>

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

二、测试代码编写

AdminController.java

package com.example.springboot_test.controller;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.HashMap;
 
 
@RestController
public class AdminController {
 
    @GetMapping("/demo01")
    public HashMap<String, Object> applyList() {
        HashMap<String, Object> res = new HashMap<>();
        res.put("code", 200);
        return res;
    }
}

SpringBootTestApplicationTests.java

package com.example.springboot_test;
 
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
 
import javax.annotation.Resource;
 
@SpringBootTest
@AutoConfigureMockMvc
class SpringBootTestApplicationTests {
    @Resource
    private MockMvc mockMvc;
    @Test
    @DisplayName("测试/demo01接口")
    void contextLoads() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/demo01")
                        .header("token", "aabbcc")
                        .param("userName", "admin"))
                .andExpect(MockMvcResultMatchers.status().isOk()) //判断http请求
                .andDo(MockMvcResultHandlers.print())  //打印返回数据
                .andExpect(MockMvcResultMatchers.jsonPath("code").value("200")) //判断返回json数据中code是否为200
                .andReturn();
    }
 
}

post请求参考

    public void approveTest() throws Exception {
        CertificateAdminApplyApproveVo tem=new CertificateAdminApplyApproveVo();
        tem.setCertificateApplyNo(1120307535526494208L);
        tem.setState(5);
        tem.setRejectReason("不同意");
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(rootPath+"/approve")
                        .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(JSON.toJSONString(tem))
                       )
                .andExpect(MockMvcResultMatchers.status().isOk()) //判断http请求
                .andDo(MockMvcResultHandlers.print())  //打印返回数据
                .andExpect(MockMvcResultMatchers.jsonPath("code").value("200")) //判断返回json数据中code是否为200
                .andReturn();
    }

三、执行测试

 
MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /demo01
       Parameters = {userName=[admin]}
          Headers = [token:"aabbcc"]
             Body = null
    Session Attrs = {}
 
Handler:
             Type = com.example.springboot_test.controller.AdminController
           Method = com.example.springboot_test.controller.AdminController#applyList()
 
Async:
    Async started = false
     Async result = null
 
Resolved Exception:
             Type = null
 
ModelAndView:
        View name = null
             View = null
            Model = null
 
FlashMap:
       Attributes = null
 
MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"code":200}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

四、问题

有些版本@AutoConfigureMockMvc注解存在,mockMvc为null

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
 
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ResourceApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApCertificateAdminControllerTest {
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;
 
    /**
     * 所有测试方法执行之前执行该方法
     * 获取mockmvc对象实例
     */
    @Before
    public void before() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
 
    @Test
    public void applyListTest() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/admin/certificate/apply/list")
                        .header("token", "aabbcc")
                        .param("userName", "admin"))
                .andExpect(MockMvcResultMatchers.status().isOk()) //判断http请求
                .andDo(MockMvcResultHandlers.print())  //打印返回数据
                .andExpect(MockMvcResultMatchers.jsonPath("code").value("200")) //判断返回json数据中code是否为200
                .andReturn();
    }
 
}

java.lang.NoClassDefFoundError: com/jayway/jsonpath/Predicate

添加依赖

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.8.0</version>
</dependency>

spring-boot-starter-test的依赖,如果项目依赖的不是spring-boot-starter-test,可以参考spring-boot-starter-test的依赖,添加即可。

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.4.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-test</artifactId>
      <version>2.4.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-test-autoconfigure</artifactId>
      <version>2.4.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.jayway.jsonpath</groupId>
      <artifactId>json-path</artifactId>
      <version>2.4.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>2.3.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>3.18.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest</artifactId>
      <version>2.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.7.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>3.6.28</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-junit-jupiter</artifactId>
      <version>3.6.28</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.skyscreamer</groupId>
      <artifactId>jsonassert</artifactId>
      <version>1.5.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.3.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.3.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.xmlunit</groupId>
      <artifactId>xmlunit-core</artifactId>
      <version>2.7.0</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <artifactId>jaxb-api</artifactId>
          <groupId>javax.xml.bind</groupId>
        </exclusion>
      </exclusions>
    </dependency>
相关文章
|
2月前
|
人工智能 Serverless 网络安全
测试
本方案利用阿里云函数计算、文件存储NAS和专有网络VPC,快速部署基于大模型的应用服务。首先,确保拥有阿里云账号并注册ModelScope账号,完成函数计算与NAS服务开通。接着,通过函数计算3.0控制台应用模板,轻松部署魔搭社区的大模型。最后,在环境详情页面访问应用域名,输入文本并提交即可体验。使用完毕后记得清理相关资源。
38 0
|
7月前
测试文章
测试文章
26 0
WAT测试介绍
本文只要介绍芯片WAT的测试环境,测试结构,测试机台,测试标准,测试项目以及测试的意义。
WAT测试介绍
|
测试技术 定位技术 开发者
从测试看需求
从测试看需求
117 0
从测试看需求
|
安全 数据挖掘 Java
如何进行有效的探索测试?
如何进行有效的探索测试?
|
监控 测试技术
|
测试技术
|
测试技术
以正常使用来进行测试
以正常使用来进行测试
106 0