1. 程式人生 > >SpringBoot開發Junit單元測試方法

SpringBoot開發Junit單元測試方法

最近在做基於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)
@SpringBootTest
public 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 {

	@Test
	public 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());
	}

	@Test
	public 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());
	}

	@Test
	public 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());
	}

	@Test
	public 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());
	}

	@Test
	public 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());
	}

	@Test
	public 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());
	}
	@Test
	public 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());
	}

	@Test
	public 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());
	}

	@Test
	public 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());
	}

	@Test
	public 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());
	}

	
	@Test
	public 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)
@SpringBootTest
public class ASysLoginServiceTest {

	@Autowired
	private IASysMsgCaptchaApi aSysMsgCaptchaApi;
	
	@Test
	public 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());
	}

}