• spring-boot 速成(11)


    一、添加依赖项:

    testCompile 'org.springframework.boot:spring-boot-starter-test:1.5.2.RELEASE'
    

    二、单元测试代码示例

    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主程序对应的类,大家根据自己的实际类名进行替换,并非测试类本身。

  • 相关阅读:
    shmget() 建立共享内存
    [转]SQL2005 连接问题处理
    [转]工作以后十不要,自勉
    C#学习笔记
    一位软件工程师6年总结(转)
    时间相关处理
    Litter Tips
    [转] VS打开解决方案时报错的处理方法
    面向对象—设计模式
    SQL Server 2000中的错误
  • 原文地址:https://www.cnblogs.com/yjmyzz/p/unit-test-with-spring-boot.html
Copyright © 2020-2023  润新知