引入单元测试依赖
- 在 pom.xml 文件中引入spring boot 单元测试依赖
<!--单元测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
创建单元测试类
- 在需要创建单元测试的类名上按 Ctrl+Shift+t,会弹出一个"Create New Test…"
- 点击"Create New Test…" 在弹出的窗口中选择需要进行单元测试的方法,然后点击OK
- src/test/java路径下,自动生成测试类"HelloWorldControllerTest"
- 除了以上自动生成测试类方法,也可以在src/test/java路径下,手动创建类,用于测试。
编写测试类内容
- 在生成的测试类的顶部添加注解
@RunWith(SpringRunner.class)
@SpringBootTest
- Controller单元测试,使用 MockMvc 实现对Http请求的模拟。
package org.mur.controller;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc// 配置 MockMvc
class HelloWorldControllerTest {
@Autowired
private MockMvc mvc;
@Test
void index() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/hello")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World!")));
}
}
- 执行测试方法。鼠标放在对应的方法,右键选择run该方法即可。
- 测试结果,测试通过。
异常处理
- 1
- 告警内容:
- Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test
- 解决方法:
- 在注解上加上 @SpringBootTest(classes = Application.class)