美文网首页
第二篇: spring-boot中的单元测试

第二篇: spring-boot中的单元测试

作者: LOC_Thomas | 来源:发表于2017-03-20 12:41 被阅读0次

前言

本篇的单元测试依附于第一篇开发的简单Hello World的微服务,并且项目代码也是和第一篇的代码在同一个项目之中。

单元测试

spring-boot 1.5.2.RELEASE里面改善了单元测试的使用方式

  1. 首先,在pom.xml里面添加
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  1. 在单元测试类
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@DirtiesContext
public class HelloWorldTest {

  @Autowired
  private TestRestTemplate restTemplate;

  @Test
  public void testHelloWorld() {
    ResponseEntity entity = this.restTemplate.getForEntity("/tutorials-01/hello", String.class);
    assertThat(entity.getBody()).isEqualTo("Hello World");
    assertThat(entity.getStatusCodeValue()).isEqualTo(200);
  }
}

第一个注解 @RunWith(SpringRunner.class) 表示要进行spring的全部流程启动单元测试,也就是说会类似于spring的正常启动启动服务

第二个注解 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) 表示使用spring-boot的方式启动单元测试,并且使用默认的端口, 这个选项主要是为了在单元测试中通过 TestRestTemplate 对象模拟 http请求

第三个注解 @DirtiesContext 表示测试上下文会影响到应用中的上下文,当测试执行后重新加载应用的上下文。

接下来就是通过 restTemplate来发起 get请求,请求本服务的地址 /tutorials-01/hello, 最后通过 assertThat 进行断言判断。

相关文章

网友评论

      本文标题:第二篇: spring-boot中的单元测试

      本文链接:https://www.haomeiwen.com/subject/wrnmnttx.html