springboot中的测试(test)

一花一世界!      2022-05-08     717

关键词:

SpringBoot2.2之后用的Junit5,所以在这里使用的Junit5。Spring Boot会默认帮我们导入包,所以不用添加依赖了。

注解:

@BeforeAll : 只执行一次,执行时机是在所有测试和 @BeforeEach 注解方法之前。
@BeforeEach:在每个测试执行之前执行。
@AfterEach :在每个测试执行之后执行。
@AfterAll: 只执行一次,执行时机是在所有测试和 @AfterEach 注解方法之后。

测试一下,代码如下

package com.example.demo;

import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
class DemoApplicationTests {
   private MockMvc mockMvc;

   @BeforeAll
   public static void  beforeAll(){
       System.out.println("begin All");
   }

   @BeforeEach
    public void beforeEach(){
       System.out.println("begin Each");
   }

   @Test
    public void test1(){
       System.out.println("test1");
   }

    @Test
    public void test2(){
        System.out.println("test2");
    }

    @AfterEach
    public void afterEach(){
        System.out.println("end Each");
    }

    @AfterAll
    public static void afterAll(){
        System.out.println("end All");
    }

}

最终的输出结果为:

begin All
begin Each
test1
end Each
begin Each
test2
end Each
end All

assert(断言)。一般的断言,无非是检查一个实例的属性(比如,判空与判非空等),或者对两个实例进行比较(比如,检查两个实例对象是否相等)等

  • assertEquals(A,B,"message"),判断A对象和B对象是否相等,这个判断在比较两个对象时调用了equals()方法。

  • assertSame(A,B,"message"),判断A对象与B对象是否相同,使用的是==操作符。

  • assertTrue(A,"message"),判断A条件是否为真。

  • assertFalse(A,"message"),判断A条件是否不为真。

  • assertNotNull(A,"message"),判断A对象是否不为null

  • assertArrayEquals(A,B,"message"),判断A数组与B数组是否相等

MockMvc。对Controller的测试需要用到MockMvc技术

首先初始化MockMvc

private MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

@Before
public void setupMockMvc(){
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

然后使用mockMvc模拟请求

模拟get请求带参数

mockMvc.perform(MockMvcRequestBuilders.get("/hello?name={name}","zeng"));

模拟post请求

mockMvc.perform(MockMvcRequestBuilders.post("/user").param("name", "zhang")) //执行传递参数的POST请求(也可以post("/user?name=zhang"))  

模拟文件上传

mockMvc.perform(MockMvcRequestBuilders.fileUpload("/fileupload").file("file", "文件内容".getBytes("utf-8")));

也可以直接使用MultiValueMap构建参数

MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("name", "zeng");
params.add("password", "123");
params.add("id", "1");
mockMvc.perform(MockMvcRequestBuilders.get("/stu").params(params));

 

模拟session和cookie

mockMvc.perform(MockMvcRequestBuilders.get("/index").sessionAttr(name, value));
mockMvc.perform(MockMvcRequestBuilders.get("/index").cookie(new Cookie(name, value)));

模拟HTTP请求头:

mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1).header(name, values));

设置请求的Content-Type:

mockMvc.perform(MockMvcRequestBuilders.get("/index").contentType(MediaType.APPLICATION_JSON_UTF8));

设置返回格式为JSON:

mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1).accept(MediaType.APPLICATION_JSON));

mockMvc处理返回结果

期望成功调用,即HTTP Status为200:

mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1))
    .andExpect(MockMvcResultMatchers.status().isOk());

期望返回内容是application/json

mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1))
    .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON));

检查返回JSON数据中某个值的内容:

mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1))
    .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("zzz"))

这里使用到了jsonPath$代表了JSON的根节点.

比较返回内容,使用content()

// 返回内容为hello
mockMvc.perform(MockMvcRequestBuilders.get("/index"))
    .andExpect(MockMvcResultMatchers.content().string("hello"));

// 返回内容是XML,并且与xmlCotent一样
mockMvc.perform(MockMvcRequestBuilders.get("/index"))
    .andExpect(MockMvcResultMatchers.content().xml(xmlContent));

// 返回内容是JSON ,并且与jsonContent一样
mockMvc.perform(MockMvcRequestBuilders.get("/index"))
    .andExpect(MockMvcResultMatchers.content().json(jsonContent));

比较forward或者redirect:

mockMvc.perform(MockMvcRequestBuilders.get("/index"))
    .andExpect(MockMvcResultMatchers.forwardedUrl("index.html"));
// 或者
mockMvc.perform(MockMvcRequestBuilders.get("/index"))
    .andExpect(MockMvcResultMatchers.redirectedUrl("index.html"));

输出响应结果:

mockMvc.perform(MockMvcRequestBuilders.get("/index"))
    .andDo(MockMvcResultHandlers.print());

在测试过程中如果要对数据库添加、删除、修改数据可以使用@Transactional,使数据能够回滚。

 

在springboot中编写mock单元测试

...意使用@Test注解标注的publicvoid方法执行之后执行;新建的springBoot项目中默认包含了spring-boot-starter-test的依赖,如果没有包含可自行在pom.xml中添加依赖。所谓的mock就是创建一个类的虚假的对象,在测试环境中,用来替换掉真实的... 查看详情

记录springboot大坑一个,在bean中如果有@test单元测试,不会注入成功

记录SpringBoot大坑一个,在bean中如果有@Test单元测试,不会注入成功记录SpringBoot大坑一个,在bean中如果有@Test单元测试,不会注入成功记录SpringBoot大坑一个,在bean中如果有@Test单元测试,不会注入成功org.springframework.beans.factory.No... 查看详情

SpringBoot Test - 可以针对默认应用程序上下文运行测试吗?

】SpringBootTest-可以针对默认应用程序上下文运行测试吗?【英文标题】:SpringBootTest-possibletoruntestsagainstthedefaultapplicationcontext?【发布时间】:2020-11-3011:13:47【问题描述】:执行SpringBoot应用程序的JUnit测试会导致应用程序的测试上... 查看详情

关于springboot的单元测试

packagecn.jhxcom.web.demo;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;impo 查看详情

springboot笔记

...,启动junit需要加载以下2个引用@RunWith(SpringRunner.class),@SpringBootTest。@Test 每个测试类都需要加上一个,选中启动即可。test测试包必须在启动类的子包里面。 packagecom.web.test;importjava.util.List;importorg.junit.Test;i 查看详情

springboot超简单的测试类demo(代码片段)

1概述SpringBoot结合Junit的简单测试类demo,流程是先引入依赖,接着编写测试类测试运行即可。2依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope><... 查看详情

springboot测试类没办法运行(代码片段)

SpringBoot测试类没办法运行,找不到运行按钮检查一下测试类的引入importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;是不是这两个,可能是.test的导包错了,导成了importorg.junit.Test; 查看详情

java教程:springboot项目如何使用test单元测试

...实体的添加修改功能,要使用到Juntil单元测试,目前使用springboot项目,jpa,maven管理,回忆起曾经用到过@Test注解,于是开始唰唰唰的写起了测试咧,然鹅,一顿报错,依赖无法注入,空指针,乱七八糟的一大通,无奈开始借助... 查看详情

springboot项目在idea中进行单元测试

SpringBoot提供了许多实用程序和注释来帮助您测试应用程序。测试由两个模块提供支持:spring-boot-test包含核心项,spring-boot-test-autoconfigure支持测试的自动配置。大多数开发人员使用spring-boot-starter-test,它会自动导入SpringBoot测试模... 查看详情

springboot启动报错可以测试吗

可以,springboot启动报错一般可以通过以下步骤进行测试:1、查看错误日志,从而确定错误的原因,比如配置错误、依赖不兼容等。2、检查和修复springboot应用的配置,比如检查配置文件的配置是否正确,检查依赖的版本是否兼... 查看详情

springboot控制层实现单元测试

packagecom.springboot.demo.controller;importorg.junit.Before;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.ht 查看详情

springboot项目进行单元测试

使用springboot开发项目时,通过简单的注解可以方便地单元测试,方式如下:一、引入springboot-test依赖<!--fortest--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test< 查看详情

springboot单元测试示例

...试模块(spring-test),用于应用程序的单元测试。 在SpringBoot中,你可以通过spring-boot-starter-test启动器快速开启和使用它。在pom.xml文件中引入maven依赖:<dependency><groupId>org.springframework.boot</groupId> 查看详情

springboot测试用例

...lass)如何运行这个测试类,这里用SpringRunner运行测试用例@SpringBootTest代表这是一个测试类@Test测试方法WEB项目需一个MVC环境新建一个User对象web层新建一个测试父类TestParentUserControllTest测试类方法上RunAs->JUnitTest则测试方法类空白... 查看详情

springboot-多环境测试

1、application.properties中添加spring.profiles.active=test2、同级目录下创建application-dev.properties、application-test.properties、application-prod.properties三个文件。3、定义端口application-dev.properties中#开发环境server.port= 查看详情

(001)springboot中测试的基础知识以及接口和controller的测试

  (一)springboot中测试的基础知识  (1)添加starter-test依赖,范围指定为test,只在执行测试时生效<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-test</artifactId&g 查看详情

springboot测试的两种方式

...b.servlet.AutoConfigureMockMvc;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.http.MediaType;importorg.springframework.test.context.junit4.SpringRu 查看详情

springboot单元测试(代码片段)

一、Service层Junit单元测试需要的jar包<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></depe 查看详情