现在大部分项目都是前后端分离的项目,在我们实际开发中大概率会遇到后端需要先出假接口的情况,这时我们就用到了数据Mock,接下来我们就来介绍下如何通过读取json文件的方式进行mock数据。
1、创建mediaVisitMock.json文件
mediaVisitMock.json
{"id":1,"name":"小明","age":23,"addr":"北京市朝阳区","phone":123456,"sex":"男"}
2、编写测试类进行测试
import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.stereotype.Component; import org.springframework.util.StreamUtils; import java.io.InputStream; import java.nio.charset.Charset; @Slf4j @Component public class InitMockRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { String mockMediaVisitData = getMockMediaVisitData(); JSONObject jsonObject = JSONObject.parseObject(mockMediaVisitData); System.out.println("jsonObject = " + jsonObject); } /** *从根目录下mediaVisitMock.json文件中读取json数据 */ private String getMockMediaVisitData() { String laststr = ""; //获取容器资源解析器 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //获取所有匹配的文件 try { Resource resources[] = resolver.getResources("mediaVisitMock.json"); for (Resource resource : resources) { InputStream input = resource.getInputStream(); laststr = StreamUtils.copyToString(input, Charset.forName("utf-8")); } log.info("文件读取成功:" + laststr); } catch (Exception e) { log.info("错误信息:" + e); } return laststr; } }
使用的时候直接在service层调用getMockMediaVisitData()读取mock的json文件进行数据mock即可