在前后端分离的场景中,后端提供接口,待开发联调完成后才能给到数据给前端,这样降低了效率并且给前端带来不便,传统的解决方式就是手动写接口的返回,然后注册网关测试数据。这样前后端可同时开发联调,但是如果响应数据的字段比较多,手动写的方式比较耗时,最近发现一个工具可以自动生成测试数据,并且支持泛型,免去了手写的烦恼。

官网地址:https://mtedone.github.io/podam/

工具名字叫做podam,看起来比较难读,翻译过来是POjo DAta Mocker

使用比较简单:

PodamFactory podamFactory = new PodamFactoryImpl();
BaseResult<ArticleListVo> result =  podamFactory.manufacturePojo(BaseResult.class, new TypeReference<ArticleListVo>(){}.getType());

TypeReference是fastjson的一个工具类

默认生成的是随机值,我们可以添加类型处理的构件,达到自定义效果

AtomicLong atomicLong = new AtomicLong(0);
DataProviderStrategy dataProviderStrategy = podamFactory.getStrategy();
// 字符串
dataProviderStrategy.addOrReplaceTypeManufacturer(String.class, new TypeManufacturer<String>() {
    @Override
    public String getType(DataProviderStrategy strategy, AttributeMetadata attributeMetadata, Map<String, Type> genericTypesArgumentsMap) {
        if (null != attributeMetadata.getAttributeName()) {
            String attributeName = attributeMetadata.getAttributeName().toLowerCase();
            if ("code".equals(attributeName)) {
                return "000000";
            }
            if ("msg".equals(attributeName) || "message".equals(attributeName)) {
                return "成功";
            }
            return "测试_" + attributeMetadata.getAttributeName() + "_" + atomicLong.getAndAdd(1L);

        } else { // 对于map
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 10; i++) {
                sb.append(PodamUtils.getNiceCharacter());
            }
            return sb.toString();
        }
    }
});
// 可再添加其他类型的值生成策略

这样生成的数据类似

{
    "code":"000000",
    "data":{
        "articleVoList":[
            {
                "createdTime":1540349337849,
                "id":42861,
                "score":22.48,
                "title":"测试_title_0",
                "type":3
            },
            {
                "createdTime":1540349339849,
                "id":71771,
                "score":47.56,
                "title":"测试_title_2",
                "type":2
            },
            {
                "createdTime":1540349341849,
                "id":87818,
                "score":16.47,
                "title":"测试_title_4",
                "type":9
            },
            {
                "createdTime":1540349343849,
                "id":53991,
                "score":98.29,
                "title":"测试_title_6",
                "type":9
            },
            {
                "createdTime":1540349345849,
                "id":83006,
                "score":5.98,
                "title":"测试_title_8",
                "type":2
            }
        ]
    },
    "msg":"成功"
}