Spring Boot构建RESTful API与单元测试

@Controller:修饰class,用来创建处理http请求的对象
@RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。

@RequestMapping:配置url映射


package com.skymr.demo.controller.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.skymr.demo.web.User;

@RestController
@RequestMapping(value = "/user")
public class UserController {

	// 创建一个线程安全的map
	private Map<Integer, User> userMap = Collections.synchronizedMap(new HashMap<Integer, User>());

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public User getUser(@PathVariable Integer id) {
		// 请求/user/{id},取得User
		// @PathVariable将url中的id绑定到参数id上
		return userMap.get(id);
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public List<User> getUsers() {
		// 取得 所有的User
		return new ArrayList<User>(userMap.values());
	}

	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String postUser(@ModelAttribute User user) {
		//RequestAttribute, 与@ModelAttribute
		//怎么通过RequestParam传参
		// 创建用户
		userMap.put(user.getId(), user);
		return "success";
	}

	@RequestMapping(value = "/", method = RequestMethod.PUT)
	public String putUser(@ModelAttribute User u) {
		User user = userMap.get(u.getId());
		if (user == null) {
			return "failed: no user.";
		}
		user.setAge(u.getAge());
		user.setName(user.getName());
		return "success";
	}
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String deleteUser(@PathVariable Integer id){
		userMap.remove(id);
		return "success";
	}
}


package com.skymr.demo;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.skymr.demo.controller.api.UserController;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Springboot01Application.class)
public class Springboot02ApplicationTests {
	
	
	//spring mvc测试
	private MockMvc mvc;

	@Before
	public void setUp() throws Exception {
		mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
	}
	
	@Test
	public void testUserCtrl() throws Exception{
		mvc.perform(MockMvcRequestBuilders.post("/user/").param("id", "1")
				.param("age", "20")
				.param("name", "skymr")
				.accept(MediaType.APPLICATION_JSON_UTF8)
				).andExpect(status().isOk())
				.andExpect(content().string(equalTo("success")));
		
		mvc.perform(MockMvcRequestBuilders.put("/user/").param("id", "1")
				.param("age", "21")
				.param("name", "skymr1")
				.accept(MediaType.APPLICATION_JSON_UTF8)
				).andExpect(status().isOk())
				.andExpect(content().string(equalTo("success")));
		
		mvc.perform(MockMvcRequestBuilders.get("/user/1")
				.accept(MediaType.APPLICATION_JSON_UTF8)
				).andExpect(status().isOk())
				.andDo(new ResultHandler() {
					@Override
					public void handle(MvcResult result) throws Exception {
						System.out.println("---" + result.getResponse().getContentAsString());
					}
				});
		
		mvc.perform(MockMvcRequestBuilders.delete("/user/1")
				.accept(MediaType.APPLICATION_JSON_UTF8)
				).andExpect(status().isOk())
				.andExpect(content().string(equalTo("success")));
		
		mvc.perform(MockMvcRequestBuilders.get("/user/")
				.accept(MediaType.APPLICATION_JSON_UTF8)
				).andExpect(status().isOk())
				.andExpect(content().string(equalTo("[]")));
	}
}
至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注解:@Controller,@RestController,RequestMapping以及一些参数绑定的注解:@PathVariable,@ModelAttribute,@RequestParam等。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值