上文java springboot測試類鑒定虛擬MVC請求 返回內容與預期值是否相同我們講了測試類中 虛擬MVC發送請求 匹配返回內容是否與預期值相同 但是 讓我意外的是 既然沒人罵我 因為我們實際開發 返回的基本都是json數據 字符串的接口場景是少數的
我們在java文件目錄下創建一個 domain 文件夾
下面創建一個user類
參考代碼如下
package com.example.webdom.domain;public class user {private int id;private String name;public void setId(int id) {this.id = id;}public void setName(String name) {this.name = name;}public int getId() {return id;}public String getName() {return name;}
}
這邊 我就設置一下最基本的 id和name 然后聲明一下對應的 get set函數
這邊 我們 controller 代碼更改如下
package com.example.webdom.controller;import com.example.webdom.domain.user;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/TextWeb")
public class TestWeb {@GetMappingpublic user getById(){user user = new user();user.setId(1);user.setName("數據管理");System.out.println("getById is running .....");return user;}
}
這里 我們直接 new 一個 user類對象 然后 set一下他的id和name
然后接口返回這個對象出去
將測試類 代碼改寫如下
package com.example.webdom;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.ContentResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class WebDomApplicationTests {@Testvoid contextLoads(@Autowired MockMvc mvc) throws Exception {MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/TextWeb");ResultActions action = mvc.perform(builder);ContentResultMatchers content = MockMvcResultMatchers.content();ResultMatcher result = content.json("{\"id\":1,\"name\":\"數據管理\"}");action.andExpect(result);}}
這里 我們因為還是判斷內容 所以依舊用content
然后 里面寫一個json格式的字符串即可
然后 我們右鍵測試函數運行
返回的json和這個json串是一樣的 自然不會 有什么問題
我們重點還是要看錯誤的 這里 我爸 name 后面加一個1 讓他匹配不上
然后 我們再次右鍵運行 出錯 是我們想要的
這個位置的內容依舊這么給力 依舊告訴你了 到底是那個字段出問題了 name
然后告訴了你區別 可以說 非常只能了