Spring Boot项目——单元测试

单元测试的作用 / 为什么要进行单元测试

  • 首先开发者要知道一点,无论什么情况下,测试一定要做!测试一定要做!测试一定要做!
  • 单元测试出现前测试方法
    • 启动整个应用,用户通过直接操作页面,操作系统进行测试——每次测试都要启动整个项目
    • 写一个测试入口main方法,调用需要测试的方法进行测试——入口一定要记得删除
  • 单元测试
    • 无论是一个方法,还是单个逻辑,既可以全面测试,又可以化整为零,单元测试
    • 代码留存,更改方法后可以复用测试代码,提升效率,同时保存测试记录

 系统环境

  • Spring Boot 2.2.1RELEASE
  • Java 8
  • Junit 5
  • Maven 3

pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.2.1.RELEASE</version>
     <scope>test</scope>
</dependency>

Controller层测试代码

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(value = "dev")
public class HttpRequestTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    @Rollback(value="false")
    public void testHello() {
        String requestResult = this.restTemplate.getForObject("http://127.0.0.1:" + port + "/test/hellp",
                String.class);
        Assertions.assertThat(requestResult).contains("Hello, spring");
    }
}
  • @ExtendWith(SpringExtension.class):让JUnit运行Spring的测试环境,获得Spring环境的上下文的支持。
  • @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 、@LocalServerPort:使用本地的一个随机端口启动服务。
  • @ActiveProfiles(value="dev"):多环境下使用的测试环境。
  • TestRestTemplate:在配置了 webEnvironment 后,Spring Boot 会自动提供一个 TestRestTemplate 实例,可用于发送 HTTP 请求。
  • @Rollback:事务是否回滚。

Service层测试代码

@ExtendWith(SpringExtension.class)
@SpringBootTest
@ActiveProfiles(value = "dev")
public class HttpRequestTest {

    @Test
    @Rollback(value="false")
    public void testHello() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.parse("2020-10-26", dtf);
        LocalDate end = LocalDate.parse("2020-10-31", dtf);
        Integer integer = XXXService.ConflictTime("10000001", start, end);
        Assert.assertThat(integer, Matchers.notNullValue());
    }
}

 

posted @ 2022-09-21 14:36  话·醉月  阅读(1125)  评论(0编辑  收藏  举报