Spring boot 1.4.2 单元测试配置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot 1.4.2 单元测试配置相关的知识,希望对你有一定的参考价值。
新版较旧版简化了很多
直接在测试类上添加
@RunWith(SpringRunner.class) @SpringBootTest(classes = 自己的启动类, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
同事注入 TestRestTemplate类 和通过 @LocalServerPort注解注入当前的端口号
具体测试代码如下:
@RunWith(SpringRunner.class) @SpringBootTest(classes = ServerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class Test { @LocalServerPort private int port; private URL base; private Gson gson = new Gson(); @Autowired private TestRestTemplate restTemplate; @Before public void setUp() throws Exception { this.base = new URL("http://localhost:" + port + "/"); } @Test public void test() { ResponseEntity<String> test = this.restTemplate.getForEntity( this.base.toString() + "/test", String.class, "test"); System.out.println(test.getBody()); } }
controller
@RestController @RequestMapping("/test") public class ProcessInstanceController { @RequestMapping(value = "", method = RequestMethod.GET) public String test() { return "Greetings from Spring Boot!"; } }
ServerApplication:
@SpringBootApplication public class ServerApplication extends SpringBootServletInitializer implements CommandLineRunner { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ServerApplication.class); } public static void main(String[] args) throws IOException { SpringApplication.run(ServerApplication.class, args); } @Override public void run(String... strings) throws Exception { System.out.println("初始化。。。。。。。。。。。。"); } }
以上是关于Spring boot 1.4.2 单元测试配置的主要内容,如果未能解决你的问题,请参考以下文章
在 Spring Boot 中使用 Hibernate 为 DAO 层配置单元测试
Spring Boot / JUnit,为多个配置文件运行所有单元测试