一、依赖
<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>