spring boot Junit5单元测试

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wljk506/article/details/99423450

依赖

<!--单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</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

展开阅读全文

spring boot 单元测试出错

02-01

2018-02-01 14:08:03.005 WARN 34600 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1406, SQLState: 22001n2018-02-01 14:08:03.005 ERROR 34600 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Data truncation: Data too long for column 'name' at row 1n2018-02-01 14:08:03.007 WARN 34600 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 1406, SQLState: HY000n2018-02-01 14:08:03.008 WARN 34600 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Data too long for column 'name' at row 1n2018-02-01 14:08:03.019 INFO 34600 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test context [DefaultTestContext@5a8e6209 testClass = ApplicationTests, testInstance = com.didispace.ApplicationTests@4f970963, testMethod = test@ApplicationTests, testException = org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not execute statement, mergedContextConfiguration = [MergedContextConfiguration@4b4523f8 testClass = ApplicationTests, locations = '', classes = 'class com.didispace.Application', contextInitializerClasses = '[]', activeProfiles = '', propertySourceLocations = '', propertySourceProperties = '', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]].n2018-02-01 14:08:03.029 INFO 34600 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@20d28811: startup date [Thu Feb 01 14:07:59 GMT+08:00 2018]; root of context hierarchyn2018-02-01 14:08:03.035 INFO 34600 --- [ Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'n 问答

没有更多推荐了,返回首页