測試類型
- 不帶參數(shù)
- 帶參數(shù)(必須傳入的參數(shù)必須填全)
- controller單元測試-攜帶session
HelloWorldController 控制器
@Controller
@RequestMapping("wechatTask")
public class HelloWorldController {
static public String HELLO = "Hello ,World";
@GetMapping("/study/helloWorld")
@ResponseBody
public IJSONResult helloWorld(){
//return "Hello ,World";
return IJSONResult.ok("Hello ,World");
}
@GetMapping("/study/hello")
@ResponseBody
public String hello(){
return HELLO;
}
@PostMapping("/study/helloParam")
@ResponseBody
//@RequestBody ==采用@RestController 不再需要這個
public IJSONResult helloParam(@RequestParam String name, @RequestParam int age){
System.out.println(name);
return IJSONResult.ok("Hello ,World :name =" +name+ ";age="+age);
}
}
類postman運行情況
控制器的測試用例HelloWorldControllerTests
@RunWith(SpringRunner.class)
@WebAppConfiguration // 開啟web應用配置
@SpringBootTest
public class HelloWorldControllerTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void helloWorld() throws Exception{ //打印出正常結果
MvcResult mvcResult = mvc.perform(
MockMvcRequestBuilders.get("/wechatTask/study/helloWorld"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println("http get方法結果:"+mvcResult.getResponse().getContentAsString());
//http get方法結果:{"code":200,"msg":"OK","data":"Hello ,World","time":1560405746459,"ok":null}
}
@Test
public void helloWorldParam() throws Exception{
MvcResult mvcResult = mvc.perform(
MockMvcRequestBuilders.post("/wechatTask/study/helloWorldParam")
.accept(MediaType.APPLICATION_JSON)
.param("name","雪梅") //注意如果是多個參數(shù)一定要全否則
.param("age","19") )
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println("http post 帶參數(shù)的結果:"+mvcResult.getResponse().getContentAsString());
//http post 帶參數(shù)的結果:{"code":200,"msg":"OK","data":"Hello ,World :name =雪梅;age=19","time":1560407516953,"ok":null}
}
@Test
public void hello() throws Exception {
mvc.perform(
MockMvcRequestBuilders
//.get("wechatTask/study/helloWorld")//回報錯 java.lang.AssertionError: Status Expected :200 Actual :404
.get("http://localhost:8080//wechatTask/study/hello")
.accept(MediaType.APPLICATION_JSON_UTF8) //MediaType.APPLICATION_JSON_UTF8
)
.andExpect(status().isOk()) // 用于判斷返回的期望值
.andExpect(content().string(equalTo(HelloWorldController.HELLO)));
//每頁異常表示成功
}
}
注意帶參數(shù)的與不帶參數(shù)的區(qū)別
控制器測試用例的運行截圖
參考文章
Spring Boot從Controller層進行單元測試
實戰(zhàn)Spring Boot 2.0系列:全局異常處理和測試