spring boot Junit5单元测试

依赖

<!--单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.5.2</version>
    <scope>test</scope>
</dependency>

fox.风

Junit5 断言

JUnit5 Jupiter断言都是 org.junit.jupiter.api.Assertions 类中static方法

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;import org.junit.jupiter.api.Assertions;
调用时候用
Assertions.assertAll();
Assertions.assertEquals();
Assertions.assertNotNull();
Assertions.assertNull();
Assertions.assertTrue();

Junit5 主要注解

@BeforeAll 类似于JUnit 4的@BeforeAll,表示使用了该注解的方法应该在当前类中所有使用了@Test@RepeatedTest@ParameterizedTest或者@TestFactory注解的方法之前执行,必须为static
@BeforeEach 类似于JUnit 4的@Before,表示使用了该注解的方法应该在当前类中每一个使用了@Test@RepeatedTest@ParameterizedTest或者@TestFactory注解的方法之前执行
@Test 表示该方法是一个测试方法
@DisplayName 为测试类或测试方法声明一个自定义的显示名称
@AfterEach 类似于JUnit 4的@After,表示使用了该注解的方法应该在当前类中每一个使用了@Test@RepeatedTest@ParameterizedTest或者@TestFactory注解的方法之后执行
@AfterAll 类似于JUnit 4的@AfterClass,表示使用了该注解的方法应该在当前类中所有使用了@Test@RepeatedTest@ParameterizedTest或者@TestFactory注解的方法之后执行,必须为static
@Disable 用于禁用一个测试类或测试方法,类似于JUnit 4的@Ignore
@ExtendWith 用于注册自定义扩展

IDEA 开发工具

先查看 项目src目录下是否有test/java 文件夹,
如果没有请自行创建,并设置(Project Structure -> Modules -> 你的模块)好Tests 属性目录

IDEA 快捷方式,在 需要创建单元测试的那个控制器类上 使用如下快捷键, 会弹出一个对话框,选择Create New Test ..., 在新的对话框中,进行一些单元测试配置,Testing library 选择JUnit5,Generate 后面两个选中(根据你的需要是否要选),Member 下 方法 ,根据你的需要选择。最后点击OK

MAC : Command+ shift +T
WIN: shift+Alt+t

案例 用户登录信息 GET

package com.foxwho.data.air.controller.web;

import com.foxwho.AacApplication;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@DisplayName("测试-用户登录信息")
@Slf4j
@ExtendWith(SpringExtension.class) //导入spring测试框架
@SpringBootTest(classes = {AacApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc //mockMvc
class IndexControllerTest {
    @Autowired
    private MockMvc mockMvc;


    @DisplayName("用户登录信息")
    @Test
    public void getUser() throws Exception {
        RequestBuilder req = MockMvcRequestBuilders.get("/public/info");
        MvcResult result = mockMvc.perform(req).andReturn();
        int httpStatus = result.getResponse().getStatus();
        String content = result.getResponse().getContentAsString();
        log.info("Response: HttpStatus={},content={}", httpStatus, content);
        Assertions.assertTrue(httpStatus == HttpStatus.OK.value());
    }

    @BeforeEach
    public void testBefore() {
        log.info("before===============");
    }

    @AfterEach
    public void testAfter() {
        log.info("after===============");
    }
}

返回:

2019-08-13 13:02:41.374  INFO [springAppName_IS_UNDEFINED,,,,] 64206 --- [           main] c.f.d.a.c.web.IndexControllerTest        : before===============
2019-08-13 13:02:41.571  INFO [springAppName_IS_UNDEFINED,,,,] 64206 --- [           main] c.h.d.d.d.s.i.SessionAdminServiceImpl    : LoginAuthDto user=Optional.empty
2019-08-13 13:02:41.574 DEBUG [springAppName_IS_UNDEFINED,,,,] 64206 --- [           main] com.foxwho.data.config.WebLogAspect   : RESPONSE : Wrapper(code=401, message=无访问权限, data={mail=, true_name=空, nick_name=空, name=空, job_no=, mobile=, id=0, avatar=, username=})
2019-08-13 13:02:41.580  INFO [springAppName_IS_UNDEFINED,,,,] 64206 --- [           main] com.foxwho.data.config.WebLogAspect   : SPEND TIME : 23,
2019-08-13 13:02:41.580 DEBUG [springAppName_IS_UNDEFINED,,,,] 64206 --- [           main] c.n.d.p.s.s.aop.RpcStrategyInterceptor   : Rpc strategy context is cleared
2019-08-13 13:02:41.720  INFO [springAppName_IS_UNDEFINED,,,,] 64206 --- [           main] c.h.d.a.c.web.IndexControllerTest        : Response: HttpStatus=200,content={
  "code" : 401,
  "message" : "无访问权限",
  "data" : {
    "mail" : "",
    "true_name" : "空",
    "nick_name" : "空",
    "name" : "空",
    "job_no" : "",
    "mobile" : "",
    "id" : 0,
    "avatar" : "",
    "username" : "空"
  }
}
2019-08-13 13:02:41.725  INFO [springAppName_IS_UNDEFINED,,,,] 64206 --- [           main] c.h.d.a.c.web.IndexControllerTest        : after===============

案例 用户登录信息 POST

package com.foxwho.data.air.controller.web;

import com.foxwho.AacApplication;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@DisplayName("测试-用户登录信息")
@Slf4j
@ExtendWith(SpringExtension.class) //导入spring测试框架
@SpringBootTest(classes = {AacApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc //mockMvc
class IndexControllerTest {
    @Autowired
    private MockMvc mockMvc;


    @DisplayName("用户登录信息-POST Json")
    @Test
    public void getUserPostJson() throws Exception {
        AacAdminDto aacAdminDto = new AacAdminDto();
        aacAdminDto.setId(1L);
        RequestBuilder req = MockMvcRequestBuilders.post("/aac/public/publicGetUser")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(JSON.toJSONString(aacAdminDto))
                ;
        MvcResult result = mockMvc.perform(req).andReturn();
        int httpStatus = result.getResponse().getStatus();
        String content = result.getResponse().getContentAsString();
        log.info("Response: HttpStatus={},content={}", httpStatus, content);
        Assertions.assertTrue(httpStatus == HttpStatus.OK.value());
    }
    
    @DisplayName("用户登录信息-POST ")
    // @Test
    public void getUserPost() throws Exception {
        MultiValueMap<String, String> params =new LinkedMultiValueMap<String, String>();
        params.add("xxx","xxxx");
        RequestBuilder req = MockMvcRequestBuilders.post("/aac/public/publicGetUser")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .header("xxx","xxx")
                // .param("xx","xxx")
                .params(params)
                ;
        MvcResult result = mockMvc.perform(req).andReturn();
        int httpStatus = result.getResponse().getStatus();
        String content = result.getResponse().getContentAsString();
        log.info("Response: HttpStatus={},content={}", httpStatus, content);
        Assertions.assertTrue(httpStatus == HttpStatus.OK.value());
    }

    @BeforeEach
    public void testBefore() {
        log.info("before===============");
    }

    @AfterEach
    public void testAfter() {
        log.info("after===============");
    }
}

部分参考
https://blog.csdn.net/swift0824/article/details/83928694

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风.foxwho

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值