Spring Boot Demo搭建
阿新 • • 發佈:2018-11-11
Spring Boot Demo搭建
controller程式碼
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();
}
}
junit測試程式碼
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("[]")));
}
}
關於Spring MVC中幾個註解的說明
@RestController:宣告在CLass上表示整個類都是返回內容,不請求轉發.它相當於是@Controller與@ResponseBody的結合體
@ModelAttribute: 表單傳遞的引數
@RequestParam: url中傳遞的引數值
@PathVariable: url中預定義的引數
關於MockMVC的說明
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)執行預期匹配,例如:
- MockMvcResultMatchers.status().isOk() 預期響應成功
- MockMvcResultMatchers.content().string(final String expectedContent) 指定預期的返回結果內容[字串]
- MockMvcResultMatchers.content().contentType(String contentType) 指定預期的返回結果的媒體型別
- MockMvcResultMatchers.forwardedUrl(final String expectedUrl) 指定預期的請求的URL連結
- MockMvcResultMathcers.redirectedUrl(final String expectedUrl) 指定預期的重定向的URL連結
當有一項不滿足時.就程式就會停止.
andReturn()返回 MvcResult [請求訪問結果]物件
getRequest()返回 MockHttpServletRequest [請求]物件