测试类型
- 不带参数
- 带参数(必须传入的参数必须填全)
- 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);
}
}
控制器的测试用例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","雪梅") //注意如果是多个参数一定要全否则
.param("age","19") )
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println("http post 带参数的结果:"+mvcResult.getResponse().getContentAsString());
//http post 带参数的结果:{"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)));
//每页异常表示成功
}
}
注意带参数的与不带参数的区别