SpringBoot测试类启动web环境及匹配测试

a>创建实体类Book,  引入lombok

package com.jun.controller.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {

    private int id;
    private String name;
    private String type;
    private String description;

}

b>创建控制层  ,模拟数据 ,响应JSON数据

package com.jun.controller;

import com.jun.controller.pojo.Book;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/books")
@RestController
public class BookController {

//    @GetMapping
//    public String getbyid(){
//
//        System.out.println("getbyid  is run...");
//
//        return "springboot";
//    }

    @GetMapping
    public Book getBook(){

        Book book = new Book(1, "java", "程序语言", "这是一本编程书");

        return book;
    }

}

c>在test包下创建测试类   设置web环境并开启mvc的虚拟调用

package com.jun;
import org.junit.jupiter.api.Test;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
//设置web环境
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启mvc的虚拟调用
@AutoConfigureMockMvc
public class WebTest {

    @Test
    void testFinal(@Autowired MockMvc mvc) throws Exception {
        MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/books");
        //执行,获取actions
        ResultActions actions = mvc.perform(builder);
        //设置预期值,与真实值进行比较,成功测试通过,失败测试失败,  isok() 预期是200;
        ResultMatcher resultStatus = MockMvcResultMatchers.status().isOk();

        //设置预期值,与真实值进行比较,成功测试通过,失败测试失败,  判断响应的json是否和真实的json一样
        ResultMatcher resultJson = MockMvcResultMatchers.content().json("{\"id\":2,\"name\":\"java\",\"type\":\"程序语言\",\"description\":\"这是一本编程书\"}");

        //设置预期值,与真实值进行比较,判断响应头是否与真实值相同
        ResultMatcher resultHeader = MockMvcResultMatchers.header().string("content-Type", "application/json");

        //真实值与预期值进行匹对
        actions.andExpect(resultStatus);
        actions.andExpect(resultHeader);
        actions.andExpect(resultJson);
    }

SpringBoot测试类启动web环境及匹配测试_第1张图片

如果预期和实际的不匹配则会报错

SpringBoot测试类启动web环境及匹配测试_第2张图片

 

SpringBoot测试类启动web环境及匹配测试_第3张图片

 SpringBoot测试类启动web环境及匹配测试_第4张图片

 

你可能感兴趣的:(springboot,笔记,spring,boot,java,spring)