import com.example.demo.entity.User;
import com.example.demo.entity.Users;
import com.example.demo.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;
/**
* Created by XB on 2018/7/18.
*/
@RestController
@RequestMapping("/users")
public class UserController {
private static Map<Integer, Users> mapdb = Collections.synchronizedMap(new HashMap<>());
@Resource
private UserService userService;
@RequestMapping(value = "/", method = RequestMethod.POST)
public String addUser(@ModelAttribute Users users){
mapdb.put(users.getId(), users);
System.out.println("users = [" + users.toString() + "]");
return "success";
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Users> getList(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize){
System.out.println("page = [" + page + "], pageSize = [" + pageSize + "]");
return new ArrayList<>(mapdb.values());
}
@RequestMapping(value = "/{username}", method = RequestMethod.GET)
public User getUser(@PathVariable String username){
return userService.getUser(username);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateUser(@PathVariable Integer id, @ModelAttribute Users user){
Users users = mapdb.get(id);
users.setName(user.getName());
users.setAge(user.getAge());
mapdb.put(id, users);
return "success";
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable Integer id){
mapdb.remove(id);
return "success";
}
@GetMapping(value = "/list")
public List<Map<String, Object>> list(){
return userService.list();
}
}
import com.example.demo.controller.UserController;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* Created by XB on 2018/7/18.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootUsersApplicationTests {
private MockMvc mvc;
@Before
public void setUp(){
mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
}
@Test
public void contextLoads() throws Exception {
RequestBuilder requestBuilder = null;
//获取列表
requestBuilder = MockMvcRequestBuilders.get("/users/");
mvc.perform(requestBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("[]")));
//添加用户
requestBuilder = MockMvcRequestBuilders.post("/users/").param("id", "1").param("name", "Spring").param("age", "22");
mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("success")));
//获取所有用户
requestBuilder = MockMvcRequestBuilders.get("/users/");
mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("[{\"id\":1,\"name\":\"Spring\",\"age\":22}]")));
//修改用户
requestBuilder = MockMvcRequestBuilders.put("/users/1").param("name", "Spring boot").param("age", "25");
mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("success")));
//获取单个用户
requestBuilder = MockMvcRequestBuilders.get("/users/1");
mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("{\"id\":1,\"name\":\"Spring boot\",\"age\":25}")));
//删除用户
requestBuilder = MockMvcRequestBuilders.delete("/users/1");
mvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("success")));
requestBuilder = MockMvcRequestBuilders.get("/users/");
mvc.perform(requestBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("[]")));
}
}
@RestController:声明在CLass上表示整个类都是返回内容,不请求转发.它相当于是@Controller与@ResponseBody的结合体
@ModelAttribute: 表单传递的参数
@RequestParam: url中传递的参数值
@PathVariable: url中预定义的参数
requestBuilder = MockMvcRequestBuilders.post("/users/").param("id", "1").param("name", "Spring").param("age", "22");
MockMvc是服务端 Spring MVC测试支持的主入口点。可以用来模拟客户端请求,用于测试
MockMvcRequestBuilders:用于构建MockHttpServletRequestBuilder,支持多种请求get、post、put、delete,
param()用于传递参数
MockHttpServletRequestBuilder,用于构建 MockHttpServletRequest,它用于作为 MockMvc的请求对象
MockMvc:
初始化MockMvc
private MockMvc mvc;
@Before
public void setUp(){
mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
}
RequestBuilder requestBuilder = null;
//获取列表
requestBuilder = MockMvcRequestBuilders.get("/users/");
mvc.perform(requestBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("[]")));
perform(RequestBuilder requestBuilder)执行请求,需要传入 MockHttpServletRequest 请求对象
andDo(ResultHandler handler)执行普通处理,例如 MockMvcResultHandlers的print() 方法用于 打印请求、响应及其他相关信息
andExpect(ResultMatcher matcher)执行预期匹配,例如:
当有一项不满足时.就程序就会停止.
andReturn()返回 MvcResult [请求访问结果]对象
getRequest()返回 MockHttpServletRequest [请求]对象