unit test - google gson

在单元测试中,很多次都要构造一些测试的实体数据,如果通过代码去构造实体,则要写很多代码而且难以维护,所以我们可以通过构造并读取json文件生成实体对象的方式来实现。

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
    <scope>test</scope>
</dependency>
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").enableComplexMapKeySerialization().create();
String sourceData = FileUtils.readFileToString(new File("src/test/resources/data/xxx.json"), "UTF-8");
xxxentityinstance = gson.fromJson(sourceData, xxxEntity.class);

File utils: import org.apache.commons.io.FileUtils;

在从json文件转DTO时,尤其是构造List<DTO>时,有可能会出现转换时想要的DTO被转成了LinkedTreeMap,这时在转换时要用TypeToken转换下。

String XXXDTOsData = FileUtils.readFileToString(new File("src/test/resources/data/xxx.json"), "UTF-8");
Type type = new TypeToken<List<xxxDTO>>() {}.getType();
List<xxxDTO> xxxDTOs = gson.fromJson(xxxDTOsData, type);

LinkedTreeMap解决方案借鉴博客:https://blog.csdn.net/qq_37402650/article/details/83240938

另外,看到一篇博客,在讲几种json转换工具的使用:https://blog.csdn.net/wangmx1993328/article/details/84385548

发布了289 篇原创文章 · 获赞 44 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/spfLinux/article/details/101604000
今日推荐