首页 > 其他分享 >Spring Boot构建RESTful API与单元测试

Spring Boot构建RESTful API与单元测试

时间:2022-09-29 14:12:07浏览次数:46  
标签:users Spring request 单元测试 andExpect User Boot id user

首先,回顾并详细说明一下 @Controller、@RestController、@RequestMapping注解。

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

下面我们尝试使用Spring MVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试。

User实体定义:

public class User { 
    private Long id; 
    private String name; 
    private Integer age; 
 
    // 省略setter和getter 
     
}

实现对User对象的操作接口

@RestController 
@RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下 
public class UserController { 
 
    // 创建线程安全的Map 
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); 
 
    @RequestMapping(value="/", method=RequestMethod.GET) 
    public List<User> getUserList() { 
        // 处理"/users/"的GET请求,用来获取用户列表 
        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 
        List<User> r = new ArrayList<User>(users.values()); 
        return r; 
    } 
 
    @RequestMapping(value="/", method=RequestMethod.POST) 
    public String postUser(@ModelAttribute User user) { 
        // 处理"/users/"的POST请求,用来创建User 
        // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数 
        users.put(user.getId(), user); 
        return "success"; 
    } 
 
    @RequestMapping(value="/{id}", method=RequestMethod.GET) 
    public User getUser(@PathVariable Long id) { 
        // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 
        // url中的id可通过@PathVariable绑定到函数的参数中 
        return users.get(id); 
    } 
 
    @RequestMapping(value="/{id}", method=RequestMethod.PUT) 
    public String putUser(@PathVariable Long id, @ModelAttribute User user) { 
        // 处理"/users/{id}"的PUT请求,用来更新User信息 
        User u = users.get(id); 
        u.setName(user.getName()); 
        u.setAge(user.getAge()); 
        users.put(id, u); 
        return "success"; 
    } 
 
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE) 
    public String deleteUser(@PathVariable Long id) { 
        // 处理"/users/{id}"的DELETE请求,用来删除User 
        users.remove(id); 
        return "success"; 
    } 
 
}

下面针对该Controller编写测试用例验证正确性,具体如下。当然也可以通过浏览器插件等进行请求提交验证。

```1
@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = MockServletContext.class) 
@WebAppConfiguration 
public class ApplicationTests { 
 
	private MockMvc mvc; 
 
	@Before 
	public void setUp() throws Exception { 
		mvc = MockMvcBuilders.standaloneSetup(new UserController()).build(); 
	} 
 
	@Test 
	public void testUserController() throws Exception { 
        // 测试UserController 
		RequestBuilder request = null; 
 
		// 1、get查一下user列表,应该为空 
		request = get("/users/"); 
		mvc.perform(request) 
				.andExpect(status().isOk()) 
				.andExpect(content().string(equalTo("[]"))); 
 
		// 2、post提交一个user 
		request = post("/users/") 
				.param("id", "1") 
				.param("name", "测试大师") 
                                .param("age", "20"); 
		mvc.perform(request) 
		        .andExpect(content().string(equalTo("success"))); 
 
		// 3、get获取user列表,应该有刚才插入的数据 
		request = get("/users/"); 
		mvc.perform(request) 
				.andExpect(status().isOk()) 
				.andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"测试大师\",\"age\":20}]"))); 
 
		// 4、put修改id为1的user 
		request = put("/users/1") 
				.param("name", "测试终极大师") 
				.param("age", "30"); 
		mvc.perform(request) 
				.andExpect(content().string(equalTo("success"))); 
 
		// 5、get一个id为1的user 
		request = get("/users/1"); 
		mvc.perform(request) 
				.andExpect(content().string(equalTo("{\"id\":1,\"name\":\"测试终极大师\",\"age\":30}"))); 
 
		// 6、del删除id为1的user 
request = delete("/users/1"); 
		mvc.perform(request) 
				.andExpect(content().string(equalTo("success"))); 
 
		// 7、get查一下user列表,应该为空 
		request = get("/users/"); 
		mvc.perform(request) 
				.andExpect(status().isOk()) 
				.andExpect(content().string(equalTo("[]"))); 
 
	} 
 
}

至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注解:@Controller,@RestController,RequestMapping以及一些参数绑定的注解:@PathVariable,@ModelAttribute,@RequestParam等。

标签:users,Spring,request,单元测试,andExpect,User,Boot,id,user
From: https://www.cnblogs.com/leepandar/p/16741304.html

相关文章

  • spring-security-oauth2-authorization-server
    旧依赖的移除长久以来,使用SpringSecurity整合oauth2,都是使用SpringSecurityOauth2这个系列的包:<dependency><groupId>org.springframework.security.oauth</grou......
  • Nacos Java Spring boot微服务配置错误 Error creating bean with name ‘configurati
    最近在学习微服务技术,在尝试Nacos的时候Java程序出错,提示Bean错误,在重新配置springboot和nacos的版本后,错误解决,下面是我用的版本,供大家参考。 Errorcreatingbean......
  • mybatis在spring mvc中的加载过程
    本地搭建了一套工程,把spring-5.2.x源码与mybatis-3.5.11源码做了整合,debug了一下mybatis-spring在springmvc中的加载过程。画了下面的图,删减了一些说明,图比较简练。后续......
  • vs2013添加单元测试
    vs2013添加单元测试要运行vs2013单元测试,那么打开VS2013选择工具(菜单)-扩展和更新,搜索并安装UnitTestGenerator  InstallUnitTestGenerator 如果不安装......
  • SpringBoot中写前端代码JSP、HTML、thymeleaf
    为什么springboot不能很好的支持jsp?:https://www.zhihu.com/question/61385975在springboot中使用jsp:https://blog.csdn.net/cflsup/article/details/123089542>>freemak......
  • Spring启动过程中实例化部分代码的分析(Bean的推断构造方法)
    【1】前言实例化这一步便是在doCreateBean方法的  instanceWrapper=createBeanInstance(beanName,mbd,args);  这段代码中。 【2】对于实例化的疑问......
  • SpringBoot整合其他框架
    SpringBoot整合Junit实现步骤搭建SpringBoot工程引入starter-test起步依赖编写测试类添加测试相关注解@RunWith(SpringRunner.class)@SpringBootTest(classes=启......
  • Spring JDBC 数据访问
    SpringJDBC数据访问SpringJDBC是Spring所提供的持久层技术,它的主要目标是降低使用JDBCAPI的门槛,以一种更直接,更简介,更简单的方式使用JDBCAPI,在SpringJDBC里,仅......
  • SpringBoot系列——加载自定义配置文件
    Java开发过程中,一些配置信息不想写到application.properties里面去,想自己弄一个配置文件,然后加载。例子如下:Employee.java类核心代码:@Configuration//用来标注一个自定......
  • SpringMVC中的数据处理
    数据处理目录数据处理1、利用SpringMVC实现1.1无需视图解析器1.2配置了视图解析器2、SpringMVC处理参数2.1处理提交数据2.1.1提交的名称和处理方法的参数名一致2.1.1......