前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring-boot 速成(11) - 单元测试

spring-boot 速成(11) - 单元测试

作者头像
菩提树下的杨过
发布2018-01-18 16:45:34
6050
发布2018-01-18 16:45:34
举报

一、添加依赖项:

代码语言:javascript
复制
testCompile 'org.springframework.boot:spring-boot-starter-test:1.5.2.RELEASE'

二、单元测试代码示例

代码语言:javascript
复制
import cn.mwee.winpos.cloud.admin.service.demo.DemoServiceProvider;
import cn.mwee.winpos.cloud.admin.service.demo.impl.HealthCheckServiceImpl;
import cn.mwee.winpos.cloud.admin.service.dto.common.DataResult;
import cn.mwee.winpos.cloud.admin.service.dto.common.PingResponse;
import cn.mwee.winpos.common.utils.json.JsonUtil;
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.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created by 菩提树下的杨过 on 13/08/2017.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoServiceProvider.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class DemoServiceTests {

    Logger log = LoggerFactory.getLogger(DemoServiceTests.class);

    @Autowired
    HealthCheckServiceImpl healthCheckService;

    @Autowired
    JsonUtil jsonUtil;

    @Test
    public void ping() {
        DataResult<PingResponse> data = healthCheckService.ping();
        log.info(jsonUtil.format(jsonUtil.toJson(data)));
    }

}

注意一下,最上面几个注解的写法,网上很多文章的示例都是低版本的注解,在1.4版本以后,有些注解已经废弃,高版本的spring-boot,请参考上面的正确写法。如果想切换profile,比如:想切换到dev环境 ,把@ActiveProfiles("test") 里面的test改成dev即可;另外@SpringBootTest(classes = DemoServiceProvider.class...)这里的classes,指SpringBootApplication主程序对应的类,大家根据自己的实际类名进行替换,并非测试类本身。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-08-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档