写给新手看的 Spring Boot 入门学习指南( 十 )

throwsException

{ mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=小明").accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print); }}

在类的上面添加@SpringBootTest,系统会自动加载 Spring Boot 容器。在日常测试中,我们就可以注入 bean 来做一些局部业务的测试。MockMvcRequestBuilders可以 post、get 请求,使用print方法会将请求和相应的过程都打印出来,如下:

MockHttpServletRequest: HTTP Method = POST Request URI = /hello Parameters = {name=[neo]} Headers = {}Handler: Type = com.neo.helloWorld.web.HelloWorldController Method = publicjava.lang.String com.neo.helloWorld.web.HelloWorldController.hello(java.lang.String)...MockHttpServletResponse: Status = 200

Error message = null

Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[16]} Content type = text/plain;

charset=ISO-8859-1

推荐阅读