SpringBoot开发Junit单元测试方法

来源:互联网 发布:2001太空漫游小说知乎 编辑:程序博客网 时间:2024/06/05 15:37

最近在做基于SSM框架的开发,使用SpringBoot代替了SpringMVC,怎么使用Junit单元测试呢?


首先在该服务的pom文件中添加支持junit的依赖:

然后在src/test/java 目录下添加一个父类,用来setup WebApplicationContext

import org.junit.Before;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.SpringApplicationConfiguration;import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.context.web.WebAppConfiguration;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import com.bycx.AuthcenterServiceApplication;@RunWith(SpringRunner.class)@SpringBootTestpublic abstract class TestSupport {protected MockMvc mvc;     @Autowired      protected WebApplicationContext webApplicationConnect;  @Before public void setUp() throws Exception { mvc =MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();}public MockHttpServletRequestBuilder post(String uri){return MockMvcRequestBuilders.post(uri).accept(MediaType.APPLICATION_JSON);}public MockHttpServletRequestBuilder get(String uri){return MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON);}}

首先对Controller测试,一定要继承之前的父类,这里用到了Mockmvc

public class ASysLoginControllerTest extends TestSupport {@Testpublic void testGetList() throws Exception{Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("pageNo", 1);params.put("pageSize", 10);params.put("isPage", true);String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/getList").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();System.out.println("status is: "+status);        Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testFindList() throws Exception{Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("pageNo", 1);params.put("pageSize", 10);params.put("isPage", true);String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/findList/").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testGetOne() throws Exception{Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("phoneNo", "13699466643");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/getOne/").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testGetById() throws Exception{Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("id", "8942d3c7708545e9854abad654099cdcffa9");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/getById/").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testDeleteById() throws Exception{Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("id", "8942d3c7708545e9854abad654099cdcffa9");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/deleteById/").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testSave() throws Exception{Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("id", "8942d3c7708545e9854abad654099675ffa9");params.put("phoneNo", "123321");params.put("loginName", "123321");params.put("loginPwd", "6666");params.put("loginType", "24200004");params.put("isAdmin", "2");params.put("certNo", "130406199102073011");params.put("loginCode", "133");params.put("instDate", "2017-10-23 18:58:27");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/save/").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testUserLogin() throws Exception {Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("loginNo", "13699466643");params.put("password", "123456");params.put("loginType", "24200004");params.put("applyType", "25800002");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/cust/login/").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();  System.out.println("status si: "+status);        Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testRegist() throws Exception {Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("loginNo", "13699466643");params.put("password", "123456");params.put("loginType", "24200004");params.put("verifyCode", "328379");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/cust/regist").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testFindPwd() throws Exception {Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("loginNo", "13699466643");params.put("password", "654321");params.put("verifyCode", "328379");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/cust/fpwd").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testModifyPwd() throws Exception {Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("loginNo", "13699466643");params.put("password", "123456");params.put("oldpassword", "654321");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/cust/mpwd").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}@Testpublic void testIsRegist() throws Exception {Page<ASysLogin> page = new Page<ASysLogin>();Map<String,Object> params = page.getParams();params.put("loginNo", "13699466643");String jsonObj = JSONObject.toJSONString(page);RequestBuilder request = null;request = post(IASysLoginFacade.REQUEST_PREFIX+"/cust/isRegist").contentType(MediaType.APPLICATION_JSON).content(jsonObj);MvcResult mvcResult = mvc.perform(request).andReturn();int status = mvcResult.getResponse().getStatus();          Assert.assertTrue("错误,正确的返回值为200", status == 200);          System.out.println(mvcResult.getResponse().getContentAsString());}}

因为统一请求格式封装在Page中,其中请求参数放在了param参数里面,请求json格式如下:

{"params":{
  "loginNo": "13699466643",
  "password": "123456",
  "loginType": "24200004",
  "applyType": "25800002",
  "imei": ""
}}

所以需要先把请求数据封装到page中然后使用fastjson转换成json格式发起post请求,返回结果在

MvcResult中,从该对象中可以获取到所有想要的返回信息,然后使用Assert判断返回结果是否正确。


然后,来测试Service,可以把Service方法拿过来,然后使用Assert判断结果即可

import static org.junit.Assert.*;import java.util.HashMap;import java.util.List;import java.util.Map;import org.junit.Assert;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.test.context.junit4.SpringRunner;import com.alibaba.fastjson.JSON;import com.bycx.comm.constant.PubTransCodeConstants;import com.bycx.rece.sys.api.IASysMsgCaptchaApi;import com.bycx.rece.sys.model.ASysMsgCaptcha;import com.cloud.frame.common.exception.BusinessException;import com.cloud.frame.common.pojo.Page;@RunWith(SpringRunner.class)@SpringBootTestpublic class ASysLoginServiceTest {@Autowiredprivate IASysMsgCaptchaApi aSysMsgCaptchaApi;@Testpublic void testCheck() {Map<String, Object> params = new HashMap<String, Object>();params.put("moble", "13699466643");Page<ASysMsgCaptcha> pageMsg = new Page<ASysMsgCaptcha>();pageMsg.setParams(params);pageMsg = aSysMsgCaptchaApi.getList(pageMsg);List<ASysMsgCaptcha> list = JSON.parseArray(pageMsg.gtResultString(),ASysMsgCaptcha.class);ASysMsgCaptcha cha = (null == list || list.size() == 0) ? null : list.get(0);System.out.println("code is: "+cha.getCode());Assert.assertEquals("419485", cha.getCode());}}