1、构建RESTful工程


gradle的build.gradle还要修改一下内容(只标注了要添加和修改的代码):

 //添加socialimplementation 'org.springframework.social:spring-social-core:1.1.6.RELEASE'implementation 'org.springframework.social:spring-social-web:1.1.6.RELEASE'implementation 'org.springframework.social:spring-social-security:1.1.6.RELEASE'implementation 'org.springframework.social:spring-social-config:1.1.6.RELEASE' //springsecurity与thymeleaf的整合implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE'//添加junit testImplementation下载的包不完整 用implementation下载implementation 'junit:junit:4.12'//修改这里:test与junit配合测试  testImplementation改为implementationimplementation 'org.springframework.boot:spring-boot-starter-test'

然后就gradle build,再导入eclipse中即可。

2、测试类和响应类

测试类模仿客户端请求,com.zzz.rss是我工程的根包,添加测试类com.zzz.rss.controller.MainController,代码如下:

package com.zzz.rss.controller;import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;//spring测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MainController {@Autowiredprivate WebApplicationContext webApplicationContext;//SpringMVC单元的独立测试类private MockMvc mockMvc;@Beforepublic void before() {//创建独立测试类mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();}//模拟客户端网址发送请求,查询user//@Testpublic void test() throws Exception {//发起一个Get请求String str = mockMvc.perform(MockMvcRequestBuilders.get("/user")//传入参数.param("username", "xing")//json形式发送请求.contentType(MediaType.APPLICATION_JSON))//期待服务器返回什么 期待返回状态码为200.andExpect(MockMvcResultMatchers.status().isOk())//期待服务器返回json中数组长度为3.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3)).andReturn().getResponse().getContentAsString();System.out.println(str);//网页地址/user/1不存在,则返回404}//模拟客户端,发送请求,匹配用户信息//@Testpublic void getInfo() throws Exception {//发起一个Get请求String str = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")//json形式发送请求.contentType(MediaType.APPLICATION_JSON))//期待服务器返回什么 期待返回状态码为200.andExpect(MockMvcResultMatchers.status().isOk())//期待服务器返回json的username值为xing.andExpect(MockMvcResultMatchers.jsonPath("$.username").value("xing")).andReturn().getResponse().getContentAsString();System.out.println(str);}//模拟客户端,发送添加用户请求//@Testpublic void addUser() throws Exception {//发起一个post请求mockMvc.perform(MockMvcRequestBuilders.post("/user/1")//json形式发送请求.contentType(MediaType.APPLICATION_JSON).content("{\"username\":\"xing\"}"))//期待服务器返回什么 期待返回状态码为200.andExpect(MockMvcResultMatchers.status().isOk())//期待服务器返回json值的id为1.andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));}//模拟客户端,发送修改用户请求  put//@Testpublic void updateUser() throws Exception {//发起一个put请求mockMvc.perform(MockMvcRequestBuilders.put("/user/1")//json形式发送请求.contentType(MediaType.APPLICATION_JSON).content("{\"username\":\"xing\",\"id\":\"1\"}"))//期待服务器返回什么 期待返回状态码为200.andExpect(MockMvcResultMatchers.status().isOk())//期待服务器返回json值的id为1.andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));}//模拟客户端,发送删除用户请求 @Testpublic void deleteUser() throws Exception {//发起一个delete请求mockMvc.perform(MockMvcRequestBuilders.delete("/user/1")//json形式发送请求.contentType(MediaType.APPLICATION_JSON))//期待服务器返回什么 期待返回状态码为200.andExpect(MockMvcResultMatchers.status().isOk());}
}

响应类是服务器端对请求响应处理,添加响应类com.zzz.rss.controller.UserController,代码如下:

package com.zzz.rss.controller;import java.util.ArrayList;
import java.util.List;import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import com.fasterxml.jackson.annotation.JsonView;
import com.zzz.rss.dto.User;//为Controller提供RestAPI
@RestController
@RequestMapping("/user")  //简化@RequestMapping(value="/user",method=RequestMethod.GET)代码
public class UserController {/*** @Title: query   * @Description: 完成查询响应* @param: @return 参数* @return: List<User> 返回类型* @throws*///@RequestParam //defaultValue 默认值  //name 传入参数的名字 ,对应上方法的参数,如果相同可以省略//required 是否必须对应传入参数,默认true,没对应上报400错误//value name别名相当于name//@RequestMapping(value="/user",method=RequestMethod.GET)@GetMapping//JsonView 步骤3、在controller上指定视图@JsonView(User.UserSimpleView.class)public List<User> query(@RequestParam(defaultValue="xingge",name="username") String username) {System.out.println(username);List<User> list = new ArrayList<User>();list.add(new User());list.add(new User());list.add(new User());return list;}//响应/user/{id}的请求//@RequestMapping(value="/user/{id}",method=RequestMethod.GET)@GetMapping("/{id}")//JsonView 步骤3、在controller上指定视图@JsonView(User.UserDetailView.class)//@PathVariable 映射{id}到id  可选填name value required属性public User getInfo(@PathVariable() String id) {User user = new User();user.setUsername("xing");return user;}//响应添加用户请求  如果POST改为GET,会显示405错误,响应和请求格式不同//@RequestMapping(value="/user/{id}",method=RequestMethod.POST)@PostMapping("/{id}")public User addUser(@RequestBody User user) {System.out.println(user.getUsername());System.out.println(user.getPassword());user.setId("1");return user;}//响应修改用户请求  //@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)@PutMapping("/{id}")public User updateUser(@RequestBody User user) {System.out.println(user.getId());System.out.println(user.getUsername());System.out.println(user.getPassword());return user;}//响应删除用户请求  //@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)@DeleteMapping("/{id}")public User deleteUser(@PathVariable String id) {System.out.println(id);return null;}
}

dto类com.zzz.rss.dto.User:

package com.zzz.rss.dto;import com.fasterxml.jackson.annotation.JsonView;public class User {//JsonView 步骤1、使用接口声明多种视图,例如是否包含密码信息public interface UserSimpleView{};public interface UserDetailView extends UserSimpleView{};private String id;private String username;private String password;//JsonView 步骤2、在值的get方法上指定视图@JsonView(UserSimpleView.class)public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}@JsonView(UserDetailView.class)public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@JsonView(UserSimpleView.class)  public String getId() {return id;}public void setId(String id) {this.id = id;}}

3、扩展

RESTful的增删改查对应 post delete put get。

在浏览器中输入的地址只能是get请求。而用测试类可以测试四种情况。用根包下的主函数运行Java Application程序后,在浏览器登录http://localhost:8080/ ,默认登录用户名为user,密码在console控制台有显示。

默认异常处理页面(404、405)换成自定义页面,添加如下目录结构即可:

使用Junit测试 RESTful相关推荐

  1. JUnit测试类完成后事务是默认 回滚的。只能查询数据,不能增删改。

    JUnit测试类完成后事务是默认 回滚的.只能查询数据,不能增删改. 在测试类或者测试方法上面加上注解 @Rollback(false)  表示事物不回滚,这样数据就可以提交到数据库中了. 转载于:h ...

  2. 创建JUNIT测试类

    建立JUNIT测试类步骤: 1 建立正常的JAVA工程 2  在JAVA工程的build path 的LIB中导入JUNIT4 3 工程中新建一个普通TEST.JAVA,在该类中在随便的一个方法上,反 ...

  3. 行意天下正文 Android Day02-Android中单元测试(junit测试)monkey测试

    Android中junit测试有2种实现方式 第1种:一般Android工程的实现方式 1.在清单文件中添加2项内容 首先在AndroidManifest.xml中加入下面红色代码: <mani ...

  4. 使用ant进行junit测试

    (绿色部分为转) 一.关于Junit 关于为什么junit.jar包不能放到lib/ext目录中: 先谈谈类装载器 java虚拟机和程序都调用ClassLoader类的loadClass的方法来加载. ...

  5. Maven找不到要运行的JUnit测试

    我有一个Maven程序,它可以正常编译. 当我运行mvn test它不会运行任何测试(在TESTs标头下显示There are no tests to run. ). 我已经用一个非常简单的设置重新创 ...

  6. Android JUnit测试说明和实例演示

    什么是 JUnit ? JUnit是采用测试驱动开发的方式,也就是说在开发前先写好测试代码,主要用来说明被测试的代码会被如何使用,错误处理等:然后开始写代码,并在测试代码中逐步测试这些代码,直到最后在 ...

  7. junit5_使用Junit测试名称

    junit5 命名测试 创建Junit测试时,通常没有方法名称的实际使用. Junit运行程序使用反射来发现测试方法,并且从版本4开始,您不再被限制以test开始方法的名称. 测试方法的名称用于文档目 ...

  8. Junit测试JAVA文件,java – Junit测试模拟文件操作

    我有一段类似于下面的代码,我被要求进行Junit测试.我们正在使用Junit,EasyMock和Spring Framework.我没有做过多少Junit测试,而且我对如何模拟下面的内容感到有点迷茫. ...

  9. junit测试NoSuchBeanDefinitionException: No bean named ‘dataSource‘ is define

    junit测试这个问题坑了我两次,印象很深刻,这都是什么bean找不到的问题,其实这个问题很简单,就是spring的配置文件没有全部加载到junit测试环境. 我们要做的就是要检查一下,所有的spri ...

最新文章

  1. 深入学习微框架:Spring Boot
  2. python pip国内源_Python 修改pip源为国内源
  3. SLAM: Orb_SLAM中的ORB特征
  4. 开源标准数据集 —— mnist(手写字符识别)
  5. Python抽象类(abc模块)
  6. 扒一扒9.3阅兵直播如何采用虚拟现实技术
  7. python3 yield_详解Python3中yield生成器的用法
  8. 使用jmeter测试接口
  9. 使用手机摄像头做网络ip摄像头用opencv中打开
  10. 解决ios微信小程序弹框点击穿透问题
  11. .ico 图标下载网站推荐
  12. “微肥”还是“歪fai”
  13. python - 正则表达式 与或非
  14. aui移动端UI框架
  15. linux学习-安装centos
  16. [Office] WPS Excel通过添加宏实现多张表格合并
  17. ⑨要写信(codevs 1697)
  18. 安装spconv踩的坑
  19. 剖析大数据、人工智能、机器学习、神经网络、深度学习五者之区别与联系
  20. 绩效从C到S,分享渣渣程序员逆袭秘诀!

热门文章

  1. c语言中include的作用,c语言include的用法是什么
  2. 在GitHub个人资料页面显示个性简历
  3. luogu1000 超级玛丽游戏
  4. 软件测试修炼之道之——重现问题
  5. 一对一直播交友源码实现即时通讯非常“有一套”
  6. 国内外自然语言处理研究机构
  7. 浅论人工智能以及朱迪亚·珀尔(Judea Pearl)的因果推理误区 道翰天琼认知智能
  8. 417. 太平洋大西洋水流问题(DFS)
  9. 前程无忧财报:招聘巨头囚于天花板
  10. 我来学网络——IIS中出现无效的应用程序池名称