一、前期配置
建立 SpringBoot项目时,会自动加入单元测试依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
也会生成单元测试文件:
其中 @SpringBootTest
除了提供单元测试的功能,还提供了一些默认的特性比如自定义环境属性,自动检索启动类,不需要额外的其他配置。
二、service 测试
(1)建立 service 类
(2)对其进行测试
三、Controller 测试
对于 Controller 测试,代码测试比较麻烦,推荐使用工具测试比如:Postman
如果环境不允许,只能通过代码测试,
(1)编写一个 Controller 类
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(String name) {
return "hello " + name;
}
@PostMapping("/book")
public Book addBook(@RequestBody Book book) {
return book;
}
}
(2)对其进行测试
@SpringBootTest
public class TestApplicationTests {
@Autowired
WebApplicationContext wac;
MockMvc mockMvc;
@Before
public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void test1() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/hello")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("name", "javaboy"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
//输入 json 格式数据测试
@Test
public void test2() throws Exception {
Book book = new Book();
book.setId(99);
book.setName("三国演义");
book.setAuthor("罗贯中");
String s = new ObjectMapper().writeValueAsString(book);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/book").contentType(MediaType.APPLICATION_JSON).content(s))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
}
这种方法相对复杂,推荐一种相对简单的方法:TestRestTemplate
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class TestApplicationTests2 {
@Autowired
TestRestTemplate testRestTemplate;
@Test
public void contextLoads() {
// 拿到响应的结果
String yolo = testRestTemplate.getForObject("/hello?name={1}", String.class, "yolo ");
System.out.println(yolo);
}
}
四、Json 测试
这里由于在 test 测试目录下加了 json 文件,所以需要在 pom文件中引入,不然测试目录的文件不会被自动打包
book.json:
{"id":99,"name":"红楼梦","author":"曹雪芹"}
<resources>
<resource>
<directory>src/test/java</directory>
<includes>
<include>**/*.json</include>
</includes>
</resource>
</resources>
package org.yolo.test;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import java.io.IOException;
/**
* @Auther: Yolo
* @Date: 2020/9/6 22:29
* @Description:
*/
@JsonTest
public class TestJson {
@Autowired
JacksonTester<Book> jacksonTester;
@Test
public void contextLoads() throws IOException {
Book book = new Book();
book.setId(99);
book.setName("红楼梦");
book.setAuthor("曹雪芹");
//判断序列化的结果是否等于 book.json 里的值
Assertions.assertThat(jacksonTester.write(book))
.isEqualToJson("book.json");
//判断序列化结果是否有一个 key 为 name
Assertions.assertThat(jacksonTester.write(book))
.hasJsonPathStringValue("@.name");
//判断序列化结果中 name 是否为 "红楼梦"
Assertions.assertThat(jacksonTester.write(book))
.extractingJsonPathStringValue("@.name")
.isEqualTo("红楼梦");
}
@Test
public void test2() throws IOException {
String content = "{\"id\":99,\"name\":\"红楼梦\",\"author\":\"曹雪芹\"}";
//反序列化,获取其中的name属性,判断是否等于“红楼梦”
Assertions.assertThat(jacksonTester.parseObject(content).getName()).isEqualTo("红楼梦");
}
}
转载:https://blog.csdn.net/nanhuaibeian/article/details/108436201
查看评论