SpringBootTest单元测试实战、SpringBoot测试进阶高级篇之MockMvc讲解

时间:2022-08-28 19:33:56

1、@SpringBootTest单元测试实战

简介:讲解SpringBoot的单元测试

1、引入相关依赖

<!--springboot程序测试依赖,如果是自动创建项目默认添加-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

2、使用

         测试类:

@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner

@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程

public class SpringBootTests { }

      

2、SpringBoot测试进阶高级篇之MockMvc讲解

简介:讲解MockMvc类的使用和模拟Http请求实战

1、增加类注解 @AutoConfigureMockMvc

@SpringBootTest(classes={XdclassApplication.class})

2、相关API

perform:执行一个RequestBuilder请求

andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则

andReturn:最后返回相应的MvcResult->Response

    代码示例:

    SampleControler.java:

 package net.xdclass.demo.controller;

 import java.util.Date;
import java.util.HashMap;
import java.util.Map; import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*; import net.xdclass.demo.domain.User; @RestController
public class SampleControler { @RequestMapping("/test/home")
public String home() {
return "xdclass";
} }

    测试:

    MockMvcTestDemo.java:

 package xdclass_springboot.demo;

 import net.xdclass.demo.XdClassApplication;

 import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; /**
* 功能描述:测试mockmvc类
*/
@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={XdClassApplication.class}) //启动整个springboot工程
@AutoConfigureMockMvc
public class MockMvcTestDemo { @Autowired
private MockMvc mockMvc; @Test
public void apiTest() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/test/home_xxx") ).
andExpect( MockMvcResultMatchers.status().isOk() ).andReturn();
int status = mvcResult.getResponse().getStatus();
System.out.println(status); } }

1、@SpringBootTest单元测试实战简介:讲解SpringBoot的单元测试1、引入相关依赖 <!--springboot程序测试依赖,如果是自动创建项目默认添加-->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>

2、使用@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程public class SpringBootTests { }