上文 java springboot測試類鑒定虛擬MVC運行值與預期值是否相同
中 我們驗證了它HTTP的返回狀態 簡單說 校驗了他 是否成功的狀態
這次 我們來不對得到的內容
我們 直接改寫測試類代碼如下
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.string("springboot");action.andExpect(result);}}
這次 我們聲明 content 表示要比對內容
然后 content.string中設置預期內容 最后比對
和我們上文的比對格式基本是一致的 只是換了寫關鍵字
這里 我們直接運行
這邊運行就通過了 因為我們最后返回的確實是個 springboot
那么 這里 我們將匹配內容改一下
這里 我們改個錯的 然后重新運行
我們可以看到 這里他就拋異常了 里面會告訴你 預期是springboot
但實際得到的是 springboot2