1、在pom文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、约定写法
单元测试代码写在src/test/java目录下。
单元测试类命名为*Test,前缀为要测试的类名。
3、单元测试代码
注解说明:
@RunWith: 用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境。
@SpringBootTest : 注解是SpringBoot自1.4.0版本开始引入的一个用于测试的注解。其中,classes
属性指定启动类;SpringBootTest.WebEnvironment.RANDOM_PORT,
会随机生成一个端口号。
/**
* @program: 单元测试
* @Date: 2019/8/12 12:07
* @Author: xxx
* @Description: webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT 会随机分配端口号
*/
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Main.class) //classes指定springboot的启动类
public class HelloTest {
@Autowired
private TestRestTemplate restTemplate; //通过TestRestTemplate进行controller的接口测试
@Autowired
private HelloProperties helloProperties;
@Autowired
private HelloService helloService;
@Test
public void helloWorldTest() {
log.info("开始测试url:{}", helloProperties.getHELLO_WORLD_URL());
ResponseModel responseModel = restTemplate.getForObject(helloProperties.getHELLO_WORLD_URL(), ResponseModel.class);
log.info("单元测试结果:{},数据:{}", responseModel.getSuccessful(), responseModel.getData());
}
@Test
public void helloWorldJava() {
log.info("开始测试url:{}", helloProperties.getHELLO_JAVA_URL());
ResponseModel responseModel = restTemplate.getForObject(helloProperties.getHELLO_JAVA_URL(), ResponseModel.class);
log.info("单元测试结果:{},数据:{}", responseModel.getSuccessful(), responseModel.getData());
}
@Test
public void testService() {
log.info("开始测试service逻辑 start");
helloService.testBranch();
log.info("开始测试service逻辑 end");
}
}