SpringBoot 单元测试
Posted liuxm-刘小明
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot 单元测试相关的知识,希望对你有一定的参考价值。
实验环境 springboot1.5.9 ,junit4.12以上
添加pom依赖
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
编写测试代码
@RunWith(SpringRunner.class) @SpringBootTest(classes = StartUpApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloControllerTest { /** * @LocalServerPort 提供了 @Value("${local.server.port}") 的代替 */ @LocalServerPort private int port; private URL base; @Autowired private TestRestTemplate restTemplate; @Before public void setUp() throws Exception { String url = String.format("http://localhost:%d/", port); System.out.println(String.format("port is : [%d]", port)); this.base = new URL(url); } /** * 向"/test"地址发送请求,并打印返回结果 * @throws Exception */ @Test public void test1() throws Exception { ResponseEntity<String> response = this.restTemplate.getForEntity( this.base.toString() + "/test", String.class, ""); System.out.println(String.format("测试结果为:%s", response.getBody())); }
参考文章 https://blog.csdn.net/limenghua9112/article/details/79694849
以上是关于SpringBoot 单元测试的主要内容,如果未能解决你的问题,请参考以下文章
java中springboot集成junit编写单元测试(实战+坑)