本文主要是介绍mock测试spring boot的CRUD服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
controller如下:
-
@RestController
-
public class GithubController {
-
@Autowired
-
private GitHubRepository repository;
-
-
@Autowired
-
private GithubEntityManager manager;
-
-
/**
-
* attention:用户名可能存在多个
-
* Details:根据用户名查询数据库
-
* @author chhliu
-
*/
-
@RequestMapping(value="github/get/users/{username}", method=RequestMethod.GET)
-
public ResultMsg<List<GitHubEntity>> getGithubByUsername(@PathVariable("username") final String username){
-
ResultMsg<List<GitHubEntity>> res = new ResultMsg<List<GitHubEntity>>();
-
try {
-
Assert.hasLength(username, "username must be not null!");
-
List<GitHubEntity> list = repository.findEntityByUserName(username);
-
res.setResponseObject(list);
-
res.setOK(true);
-
} catch (Exception e) {
-
res.setErrorMsg(e.getMessage());
-
res.setOK(false);
-
}
-
return res;
-
}
-
-
/**
-
* attention:id唯一
-
* Details:根据id查询数据库
-
* @author chhliu
-
*/
-
@RequestMapping(value="github/get/user/{id}", method=RequestMethod.GET)
-
public ResultMsg<GitHubEntity> getGithubById(@PathVariable("id") final int id){
-
ResultMsg<GitHubEntity> msg = new ResultMsg<GitHubEntity>();
-
try {
-
boolean isExists = repository.exists(id);
-
if(isExists){
-
GitHubEntity en = repository.findOne(id);
-
msg.setResponseObject(en);
-
msg.setOK(true);
-
}else{
-
msg.setErrorMsg("the record id is not exist!");
-
msg.setOK(false);
-
}
-
} catch (Exception e) {
-
msg.setErrorMsg(e.getMessage());
-
msg.setOK(false);
-
}
-
return msg;
-
}
-
-
/**
-
* attention:
-
* Details:查询所有的结果,并分页和排序
-
* @author chhliu
-
*/
-
@RequestMapping(value="github/get/users/page", method=RequestMethod.GET)
-
public ResultMsg<Page<GitHubEntity>> findAllGithubEntity(final int pageOffset, final int pageSize, final String orderColumn){
-
ResultMsg<Page<GitHubEntity>> res = new ResultMsg<Page<GitHubEntity>>();
-
try {
-
res.setResponseObject(manager.findAllGithubEntity(pageOffset, pageSize, orderColumn));
-
res.setOK(true);
-
} catch (Exception e) {
-
res.setErrorMsg(e.getMessage());
-
res.setOK(false);
-
}
-
return res;
-
}
-
-
/**
-
* attention:
-
* Details:插入一个实体到数据库中
-
* @author chhliu
-
*/
-
@Modifying
-
@RequestMapping(value="github/post" ,method=RequestMethod.POST)
-
public ResultMsg<GitHubEntity> saveGithubEntity(@RequestBody final GitHubEntity entity){
-
ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>();
-
try {
-
Assert.notNull(entity, "the insert record must not be null!");
-
res.setResponseObject(repository.save(entity));
-
res.setOK(true);
-
} catch (Exception e) {
-
res.setErrorMsg(e.getMessage());
-
res.setOK(false);
-
}
-
return res;
-
}
-
-
/**
-
* attention:
-
* Details:更新一个实体类
-
* @author chhliu
-
*/
-
@Modifying
-
@RequestMapping(value="github/put", method=RequestMethod.PUT)
-
public ResultMsg<GitHubEntity> updateGithubEntity(final GitHubEntity entity){
-
ResultMsg<GitHubEntity> res = new ResultMsg<GitHubEntity>();
-
try {
-
Assert.notNull(entity, "the update record must not be null!");
-
Assert.notNull(entity.getId(), "the record id must not be null!");
-
boolean isExists = repository.exists(entity.getId());
-
if(isExists){
-
GitHubEntity en = repository.findOne(entity.getId());
-
if(null != en){
-
en.setCodeSnippet(entity.getCodeSnippet());
-
en.setCodeUrl(entity.getCodeUrl());
-
en.setProjectUrl(entity.getProjectUrl());
-
en.setSensitiveMessage(entity.getSensitiveMessage());
-
en.setSpriderSource(entity.getSpriderSource());
-
en.setSpriderUrl(entity.getSpriderUrl());
-
en.setUserName(entity.getUserName());
-
res.setResponseObject(repository.save(en));
-
res.setOK(true);
-
}else{
-
res.setOK(false);
-
res.setErrorMsg("doesn't find the record by id!");
-
}
-
}else{
-
res.setOK(false);
-
res.setErrorMsg("the record id is not exist!");
-
}
-
-
} catch (Exception e) {
-
res.setErrorMsg(e.getMessage());
-
res.setOK(false);
-
}
-
return res;
-
}
-
-
/**
-
* attention:
-
* Details:根据id删除一条数据
-
* @author chhliu
-
*/
-
@RequestMapping(value="github/delete/{id}", method=RequestMethod.DELETE)
-
public ResultMsg<Boolean> deleteGithubEntity(@PathVariable("id") final int id){
-
ResultMsg<Boolean> res = new ResultMsg<Boolean>();
-
try {
-
Assert.notNull(id);
-
boolean isExist = repository.exists(id);
-
if(isExist){
-
repository.delete(id);
-
res.setOK(true);
-
res.setResponseObject(true);
-
}else{
-
res.setOK(false);
-
res.setErrorMsg("the record id is not exist!");
-
}
-
} catch (Exception e) {
-
res.setErrorMsg(e.getMessage());
-
res.setOK(false);
-
}
-
return res;
-
}
-
}
测试代码如下:
-
@RunWith(SpringJUnit4ClassRunner.class)
-
@SpringBootTest(classes = CldpApplication.class)
-
@WebAppConfiguration
-
public class GitHubControllerTest {
-
@Autowired
-
private GithubController controller;
-
private MockMvc mvc;
-
@Before
-
public void setUp() throws Exception {
-
mvc = MockMvcBuilders.standaloneSetup(controller).build();
-
}
-
/**
-
* attention:
-
* Details:测试查询
-
* @author chhliu
-
* 创建时间:2016-12-7 下午3:41:34
-
* @throws Exception
-
* void
-
*/
-
@Test
-
public void getGitHubEntityByUsername() throws Exception {
-
MvcResult result = mvc.perform(
-
MockMvcRequestBuilders.get("/github/get/users/Datartisan")
-
.accept(MediaType.APPLICATION_JSON))
-
.andReturn();
-
int statusCode = result.getResponse().getStatus();
-
Assert.assertEquals(statusCode, 200);
-
String body = result.getResponse().getContentAsString();
-
System.out.println("body:"+body);
-
}
-
/**
-
* attention:
-
* Details:测试查询
-
* @author chhliu
-
* 创建时间:2016-12-7 下午3:41:49
-
* @throws Exception
-
* void
-
*/
-
@Test
-
public void getGitHubEntityById() throws Exception {
-
MvcResult result = mvc.perform(
-
MockMvcRequestBuilders.get("/github/get/user/721")
-
.accept(MediaType.APPLICATION_JSON))
-
.andReturn();
-
int statusCode = result.getResponse().getStatus();
-
Assert.assertEquals(statusCode, 200);
-
String body = result.getResponse().getContentAsString();
-
System.out.println("body:"+body);
-
}
-
/**
-
* attention:
-
* Details:测试分页查询
-
* @author chhliu
-
* 创建时间:2016-12-7 下午3:42:02
-
* @throws Exception
-
* void
-
*/
-
@Test
-
public void getGitHubEntityPage() throws Exception {
-
MvcResult result = mvc.perform(
-
MockMvcRequestBuilders.get("/github/get/users/page").param("pageOffset", "0")
-
.param("pageSize", "10").param("orderColumn", "id").accept(MediaType.APPLICATION_JSON))
-
.andReturn();
-
int statusCode = result.getResponse().getStatus();
-
Assert.assertEquals(statusCode, 200);
-
String body = result.getResponse().getContentAsString();
-
System.out.println("body:"+body);
-
}
-
/**
-
* attention:
-
* Details:测试插入,方式一,此方式需要controller中方法参数前没有@RequestBody
-
* @author chhliu
-
* 创建时间:2016-12-7 下午3:42:19
-
* @throws Exception
-
* void
-
*/
-
@Test
-
public void postGithubEntity() throws Exception{
-
RequestBuilder request = MockMvcRequestBuilders.post("/github/post")
-
.param("codeSnippet", "package")
-
.param("codeUrl", "http://localhost:8080/code")
-
.param("projectUrl", "http://localhost:8080")
-
.param("userName", "chhliu")
-
.param("sensitiveMessage", "love")
-
.param("spriderSource", "CSDN")
-
.contentType(MediaType.APPLICATION_JSON_UTF8);
-
MvcResult result = mvc.perform(request)
-
.andReturn();
-
int statusCode = result.getResponse().getStatus();
-
Assert.assertEquals(statusCode, 200);
-
String body = result.getResponse().getContentAsString();
-
System.out.println("body:"+body);
-
}
-
/**
-
* attention:
-
* Details:测试插入,方式二,此方式需要controller中方法参数前加@RequestBody
-
* @author chhliu
-
* 创建时间:2016-12-7 下午3:42:19
-
* @throws Exception
-
* void
-
*/
-
@Test
-
public void postGithubEntity1() throws Exception{
-
GitHubEntity entity = new GitHubEntity();
-
entity.setUserName("xyhg");
-
entity.setSpriderSource("ITeye");
-
entity.setCodeUrl("http://localhost:8080");
-
ObjectMapper mapper = new ObjectMapper();
-
MvcResult result = mvc.perform(MockMvcRequestBuilders.post("/github/post")
-
.contentType(MediaType.APPLICATION_JSON_UTF8)
-
.content(mapper.writeValueAsString(entity)))
-
.andExpect(MockMvcResultMatchers.status().isOk())
-
.andReturn();
-
int statusCode = result.getResponse().getStatus();
-
Assert.assertEquals(statusCode, 200);
-
String body = result.getResponse().getContentAsString();
-
System.out.println("body:"+body);
-
}
-
/**
-
* attention:
-
* Details:测试更新和插入类似
-
* @author chhliu
-
* 创建时间:2016-12-7 下午3:42:32
-
* @throws Exception
-
* void
-
*/
-
@Test
-
public void putGithubEntity() throws Exception{
-
RequestBuilder request = MockMvcRequestBuilders.put("/github/put")
-
.param("id", "719")
-
.param("codeSnippet", "import java.lang.exception")
-
.param("codeUrl", "http://localhost:8080/code")
-
.param("projectUrl", "http://localhost:8080")
-
.param("userName", "xyh")
-
.param("sensitiveMessage", "love")
-
.param("spriderSource", "CSDN");
-
MvcResult result = mvc.perform(request)
-
.andReturn();
-
int statusCode = result.getResponse().getStatus();
-
Assert.assertEquals(statusCode, 200);
-
String body = result.getResponse().getContentAsString();
-
System.out.println("body:"+body);
-
}
-
@Test
-
public void deleteGithubEntity() throws Exception{
-
RequestBuilder request = MockMvcRequestBuilders.delete("/github/delete/719");
-
MvcResult result = mvc.perform(request)
-
.andReturn();
-
int statusCode = result.getResponse().getStatus();
-
Assert.assertEquals(statusCode, 200);
-
String body = result.getResponse().getContentAsString();
-
System.out.println("body:"+body);
-
}
-
}
其中@SpringBootTest是@SpringApplicationConfiguration的替代注解,因为后者在spring boot1.4之后就被废弃了。
下面来看下这3个注解的作用
@RunWith:引入spring-test测试支持
@SpringBootTest:指定Spring boot工程的Application启动类
@WebAppConfiguration:Spring boot用来模拟ServletContext,并加载上下文
测试过程中,我们需要构建MockMvc,通过该类可以模拟发送,接收Restful请求
测试效果示例如下:
body:{"errorCode":null,"errorMsg":null,"responseObject":{"id":734,"createTime":1481103420245,"spriderSource":"ITeye","spriderUrl":null,"userName":"xyhg","projectUrl":null,"codeUrl":"http://localhost:8080","codeSnippet":null,"sensitiveMessage":null},"ok":true}
可以发现,测试通过了,并且返回结果和在浏览器中输入对应的url返回的结果是一致的!
这篇关于mock测试spring boot的CRUD服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!