controller
package com.example.springBoot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springBoot.pojo.Hello;
//@RestController的意思就是controller里面的方法都以json格式输出,不用再写什么jackjson配置的了!
@RestController
public class HelloWorldController {
@GetMapping("/helloworld")
public Hello helloworld(Hello hello){
hello.setAge("19");
hello.setName("name");
return hello;
}
}
pojo
package com.example.springBoot.pojo;
public class Hello {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
单元测试
打开的src/test/下的测试入口,编写简单的http请求来测试;使用mockmvc进行,利用MockMvcResultHandlers.print()打印出执行结果。
package com.example.springBoot;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.example.springBoot.controller.HelloWorldController;
//表示使用Spring Test组件进行单元测试,其中SpringRunner继承类SpringJUnit4ClassRunner。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
private MockMvc mockMvc;
//注入web环境的ApplicationContext容器:mvc = MockMvcBuilders.webAppContextSetup(context).build();
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void getHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/helloworld").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}
打印结果:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /helloworld
Parameters = {}
Headers = {Accept=[application/json]}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.example.springBoot.controller.HelloWorldController
Method = public com.example.springBoot.pojo.Hello com.example.springBoot.controller.HelloWorldController.helloworld(com.example.springBoot.pojo.Hello)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"name":"name","age":"19"}
Forwarded URL = null
Redirected URL = null
Cookies = []