01.SpringBoot 与 JUnit
有了单元测试才能更好的写代码哟!
0、单元测试
单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如C语言中单元指一个函数,Java里单元指一个类,图形化的软件中可以指一个窗口或一个菜单等。总的来说,单元就是人为规定的最小的被测功能模块。单元测试是在软件开发过程中要进行的最低级别的测试活动,软件的独立单元将在与程序的其他部分相隔离的情况下进行测试。单元测试一般由程序员本人去编写一段代码去证明自己的代码的正确性。
1、JUnit
1.1、 简介
JUnit 是一个 Java 编程语言的单元测试框架。JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量。
2、SpringBoot 与JUnit
2.1、在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.2、使用SpringBoot的Application做为启动类编写一个简单的测试程序
@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleTest {
@Test
public void doTest() {
int a = 1;
int b = 2;
int sum = a+b;
Assert.assertEquals(sum , 3);
}
}
代码解释:
- @RunWith:标识JUnit的运行环境,@RunWith(SpringRunner.class),将Spring和JUnit链接在一起
- @SpringBootTest 加载ApplicationContext,启动spring容器,可以使用@SpringBootTest(class=‘AppApplication.class’)标识启动类
- @Test 生命需要测试的方法
2.3 Web模拟测试
针对上期写的Example的Hello方法写一个关于RestfulAPI的JUnit测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ExampleTest {
private static Logger logger = LoggerFactory.getLogger(UserControllerTest.class);
@Autowired
private MockMvc mockMvc; //模拟web环境
@Test
public void hello() throws Exception {
// 1、创建连接
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/");
// 2、获取响应结果
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
// 3、打印结果
logger.info(result.getResponse().getContentAsString());
}
}
代码解释:
- @RunWith:标识JUnit的运行环境,@RunWith(SpringRunner.class),将Spring和JUnit链接在一起
- @SpringBootTest 加载ApplicationContext,启动spring容器,可以使用@SpringBootTest(class=‘AppApplication.class’)标识启动类
- @AutoConfigureMockMvc 自动配置mockMvc的单元测试,不加这个注解会报
- @Test 生命需要测试的方法