- pom依赖
有以下依赖即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
- 文件夹层次
保证
test
文件夹下,与main
文件夹下的结构是一样:
![]()
3.把web
模块的配置,移植到service
模块的test
下
项目中的配置文件和启动类,一般都在
web
模块下,但是我们需要在service层跑单元测试,那么就需要把这些东西给service
模块复制一份。
先复制配置文件:
配置文件
配置文件搞定之后,需要在service模块的pom文件,加下以下内容,确保单元测试跑的时候,可以读取配置文件:![]()
接下来复制启动类,放在test下根目录即可:![]()
- 编写测试类基类
这里编写一个测试类基类,以后有其他功能的测试类,都可以继承这个类:![]()
代码:
package com.example.service;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplication.class)
public class AbstractContextServiceTest {
}
- 编写功能测试类
注意,测试类包名要与被测试类完全一致:
![]()
代码:
package com.example.service.test;
import com.example.pojo.TestPojo;
import com.example.service.AbstractContextServiceTest;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.jupiter.api.Assertions.*;
class TestServiceTest extends AbstractContextServiceTest {
@Autowired
private TestService testService;
@Test
void getTestData() {
TestPojo testData = testService.getTestData();
Assert.assertEquals("北京 is a busy city", testData.getTestData());
}
}
- 运行测试类
点击
Run with Coverage
选项,可以看下单侧的覆盖率:
![]()
单测通过,绿色代表覆盖到的代码:
![]()
网友评论