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

前言

本篇的单元测试依附于第一篇开发的简单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 进行断言判断。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容