spring-boot项目的单元测试

来源:互联网 发布:跨平台数据库开发工具 编辑:程序博客网 时间:2024/06/06 07:49

参考文章

Spring Boot Junit单元测试

正文

引入maven依赖

<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope></dependency>

编写测试代码,详细代码如下:

import xx.SmsClient;import org.junit.Test;import org.junit.runner.RunWith;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.SpringApplicationConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * Created by hua on 2016/6/29. */@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = VaccineFrontStartUp.class)// 指定spring-boot的启动类@ActiveProfiles("de")public class SMSClientTest {    private static final Logger logger = LoggerFactory.getLogger("TestSMS");    @Autowired    private SmsClient smsClient;    @Test    public void testSendSms() {        logger.info(String.format("smsClient:%s", smsClient));        String sendResult = smsClient.sendSMS("15600000001", "2016.06.29");        logger.info(String.format("发送结果为:%s", sendResult));    }}

总结

可以看到,对spring-boot项目进行单元测试是件容易的事儿,需要添加spring-boot-starter-test依赖,然后
使用@RunWith@SpringApplicationConfiguration注解,然后引入自己要测试的bean(在示例代码中测试的是一个短信发送的bean),调用指定方法进行测试即可。
使用@ActiveProfiles(“de”)来指定活动的profile


技术越来越易用,要勇于尝试

1 1