该工具类主要实现了从配置文件读取指定位置的json数据字符串转为Java对于JSON对象(com.alibaba.fastjson.JSONObject,jar包下载,commons-logging-1.1.3.jar下载),另外实现读取默认classpath根目录下的文本文件转为字符串,从而用这两种方式的提供作为mock开发测试提供给代码数据。
import java.io.BufferedInputStream;@b@import java.util.Properties;@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@import com.alibaba.fastjson.JSONObject;@b@@b@public class MockUtils {@b@ @b@ private static final Log log = LogFactory.getLog(MockUtils.class);@b@ private static String MOCK_FILE_NAME = "mock.properties";@b@ @b@ public static String getStringResponse(String fileName){@b@ String responseString = "";@b@ BufferedInputStream bs = null;@b@ StringBuilder sb = new StringBuilder();@b@ try{@b@ bs = new BufferedInputStream(MockUtils.class.getClassLoader().getResourceAsStream(fileName));@b@ int byteReade = 0;@b@ byte[] buffer = new byte[1024];@b@ while((byteReade = bs.read(buffer)) != -1){@b@ sb.append(new String(buffer,0, byteReade,"utf-8"));@b@ }@b@ responseString = sb.toString();@b@ }catch(Exception e){@b@ log.error("没有读取到mock文件+"+fileName, e);@b@ }finally {@b@ if (bs != null) {@b@ try {@b@ bs.close();@b@ } catch (Exception e) {@b@ log.error("", e);@b@ }@b@ }@b@ }@b@ return responseString;@b@ }@b@ @b@ public static JSONObject getJsonResponse(String fileName){@b@ JSONObject js = new JSONObject();@b@ js = JSONObject.parseObject(getStringResponse(fileName));@b@ return js;@b@ }@b@ @b@ public static String getStringResponse(){@b@ String fileName = "";@b@ String responseString = "";@b@ BufferedInputStream bs = null;@b@ Properties p = new Properties();@b@ try{@b@ bs = new BufferedInputStream(MockUtils.class.getClassLoader().getResourceAsStream(MOCK_FILE_NAME));@b@ p.load(bs);@b@ fileName = p.getProperty("mock.server.file.name");@b@ responseString = getStringResponse(fileName);@b@ }catch(Exception e){@b@ log.error("没有读取到mock对应的配置文件:"+MOCK_FILE_NAME, e);@b@ }finally {@b@ log.info(responseString);@b@ if (bs != null) {@b@ try {@b@ bs.close();@b@ } catch (Exception e) {@b@ log.error("", e);@b@ }@b@ }@b@ }@b@ return responseString;@b@ }@b@ @b@ public static JSONObject getJsonResponse(){@b@ JSONObject js = new JSONObject();@b@ js = JSONObject.parseObject(getStringResponse());@b@ return js;@b@ }@b@ @b@ public static JSONObject getJsonResponseByKey(String key){@b@ JSONObject js = getJsonResponse();@b@ return js.getJSONObject(key);@b@ }@b@ @b@ public static String getStringResponseByKey(String key){@b@ return getJsonResponseByKey(key).toJSONString();@b@ }@b@}