Java项目中,现在基本上都是前后端分离了,后端全是接口,为了提高系统质量,减少bug,其中一个方法,就是对后端接口做单元测试,编写单元测试,由于出现额外工作量,大部分Java工程师有些抵触心理,但有些公司会要求程序员必须写单元测试。
下面介绍一种快速实现单元测试方法,分享给大家,欢迎留言讨论。
目录
1.接口统一返回类
2.Post请求方法
3.Junit实现
1.接口统一返回类
public class ResponsePacket extends CommonBean {
public static int STATUS_CODE_SUCESS=0;//0成功
public static int STATUS_CODE_FAIL=-1;//-1失败
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 错误描述(null:表示成功 其他表示错误信息)提示给用户的
*/
private String errorMsg;
/**
* 返回状态码 0成功 其他:错误
*/
private int statusCode;
/**
* 返回的数据
*/
private Object data;
/**
* (建议字段)请求错误信息,提示给前端排查错误。例:Token expired or missing,(ps:也可以统一使用errorMsg字段,文中提示给用户,英文提示给前端排查错误。)
*/
private String errorHint;
public Object getData() {
return data;
}
public void setData(Object data) {
if (data == null) {
this.data = null;
} else if (data == "") {
this.data = null;
} else {
this.data = data;
}
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getErrorHint() {
return errorHint;
}
public void setErrorHint(String errorHint) {
this.errorHint = errorHint;
}
public ResponsePacket() {
super();
}
}
CommonBean.java
这个类是个人习惯,为了方便调试打印,可以去掉。
public class CommonBean implements java.io.Serializable {
/**
* The Generated SerialVersionUID.
*/
private static final long serialVersionUID = -1327286344329810029L;
/**
* Common implement equals method.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CommonBean)) {
return false;
}
return EqualsBuilder.reflectionEquals(this, obj);
}
/**
* Generate the hash code.
*/
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* Common implement toString method.
*/
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
2.Post请求方法
public static String getJsonData(String urls,int command,String json) {
StringBuffer sb=new StringBuffer();
try {
// 创建url资源
URL url = new URL(urls);
// 建立http连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置允许输出
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// 设置不用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件类型:
conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
// 设置接收类型否则返回415错误
conn.setRequestProperty("accept","application/json");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 设置文件类型:
conn.setRequestProperty("contentType", "application/json");
conn.setRequestProperty("command", command+"");
// 开始连接请求
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
// 写入请求的字符串
out.write(json.getBytes());
out.flush();
out.close();
//System.out.println(conn.getResponseCode());
// 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
//System.out.println("连接成功");
// 请求返回的数据
InputStream in1 = conn.getInputStream();
try {
String readLine=new String();
BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
while((readLine=responseReader.readLine())!=null){
sb.append(readLine).append("\n");
}
responseReader.close();
//System.out.println(sb.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.out.println("error++");
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
3.Junit实现
//本地项目访问地址
String serverUrl="http://localhost:8080/weixin/api.do";
//单元测试接口列表
HashMap<Integer, String > myMap = new HashMap<Integer, String>(){{
put(MiniAppDefineConstant.GET_GOODS_LIST,"1获取商品列表");
put(MiniAppDefineConstant.GET_GOODS_INFO,"3查询商品详情");
put(MiniAppDefineConstant.GOODS_COLLECT_LIST,"62收藏列表");
put(MiniAppDefineConstant.GOODS_COLLECT_ADD,"63收藏");
put(MiniAppDefineConstant.GOODS_COLLECT_DEL,"64取消收藏");
}};
/**
* 单元测试主入口
*/
@Test
public void miniAppMain() {
miniApp(MiniAppDefineConstant.GET_GOODS_LIST);//1获取商品列表
miniApp(MiniAppDefineConstant.GET_GOODS_INFO);//3查询商品详情
miniApp(MiniAppDefineConstant.GOODS_COLLECT_ADD);//63收藏
miniApp(MiniAppDefineConstant.GOODS_COLLECT_LIST);//62收藏列表
miniApp(MiniAppDefineConstant.GOODS_COLLECT_DEL);//64取消收藏
}
//单元测试具体实现
public void miniApp(int command) {
String json="";
if(command==MiniAppDefineConstant.GET_GOODS_LIST){//获取商品列表
json="{\"goodsName\":\"测试\",\"openId\":\"o-1234zXBPJ1234c1OrNpzql1234\",\"page\":1,\"count\":10}";
}else if(command==MiniAppDefineConstant.GET_GOODS_INFO){//查询商品详情
json="{\"goodsId\":70,\"openId\":\"o-1234zXBPJ1234c1OrNpzql1234\"}";
}else if(command==MiniAppDefineConstant.GOODS_COLLECT_LIST){//收藏列表
json="{\"goodsId\":70,\"openId\":\"o-1234zXBPJ1234c1OrNpzql1234\",\"page\":1,\"count\":10}";
}else if(command==MiniAppDefineConstant.GOODS_COLLECT_ADD){//收藏
json="{\"goodsId\":70,\"openId\":\"o-1234zXBPJ1234c1OrNpzql1234\"}";
}else if(command==MiniAppDefineConstant.GOODS_COLLECT_DEL){//取消收藏
json="{\"goodsId\":70,\"openId\":\"o-1234zXBPJ1234c1OrNpzql1234\"}";
}
System.out.println(command+"//"+myMap.get(command)+"------------"+json);
ResponsePacket responsePacket=JsonUtil.fromJson(getJsonData(serverUrl,command,json),ResponsePacket.class);
assertEquals(ResponsePacket.STATUS_CODE_SUCESS,responsePacket.getStatusCode());
}
4.单元测试运行结果
都通过单元测试接口
20003//1获取商品列表------------{"goodsName":"测试","openId":"o-1234zXBPJ1234c1OrNpzql1234","page":1,"count":10}
20005//3查询商品详情------------{"goodsId":70,"openId":"o-1234zXBPJ1234c1OrNpzql1234"}
21002//63收藏------------{"goodsId":70,"openId":"o-1234zXBPJ1234c1OrNpzql1234"}
21001//62收藏列表------------{"goodsId":70,"openId":"o-1234zXBPJ1234c1OrNpzql1234","page":1,"count":10}
21003//64取消收藏------------{"goodsId":70,"openId":"o-1234zXBPJ1234c1OrNpzql1234"}Process finished with exit code 0
部分接口没有通过测试结果截图