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