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

 

-- auto-generated definition create table user_relationships ( id int auto_increment primary key, user_id int not null, related_user_id int not null, relationship_type varchar(20) null, created_at timestamp default CURRENT_TIMESTAMP null, constraint unique_relationship unique (user_id, related_user_id), constraint user_relationships_ibfk_1 foreign key (user_id) references user (id) on delete cascade, constraint user_relationships_ibfk_2 foreign key (related_user_id) references user (id) on delete cascade ); create index related_user_id on user_relationships (related_user_id); -- auto-generated definition create table user ( id int auto_increment primary key, username varchar(50) not null, password varchar(255) not null, email varchar(100) null, role varchar(20) default 'user' null, constraint username unique (username) ); 这是我现有的数据库代码 以下是我任务书的内容 开发平台IDEA; 后台数据库为MySQL 参考现有的热门旅游平台 2.毕业设计(论文)的内容和要求(包括技术要求、工作要求和功能要求等): 根据指导教师提供的原始材料,经过细致的需求分析,开发一个能够服务于老 年人、满足用户使用需要的旅游平台。 本课题要求学生学习Java Spring Boot以及kotlin开发技术,参考现有的各家 旅游平台系统,设计一个服务于老年人的旅游平台,平台需要包含游客与导游两 种不同用户的注册和登录、目的地搜索、实时定位游客与导游、行程规划、用户 评价、游客一键拨通导游电话、旅行期间推送旅游行程相关信息等功能,实现一 个服务于老年人的旅游平台系统。 我现在要做一个服务于老年人的旅游系统的用户注册与登录模块,后端使用springboot来编写,前端使用android studio用kotlin来编写,后续需要让前后端互动起来,现在先生成一个完备的前端代码(代码中要包含import等代码以及要有文件构建)要给出你所有文件的所有代码,不可以有任何的省略,并且对你生成的代码要进行检查是否完整不缺少任何的文件与代码 依赖代码格式如下plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.kapt) } android { namespace = "com.example.tourism" compileSdk = 34 buildFeatures { viewBinding = true dataBinding = true } defaultConfig { applicationId = "com.example.touris
03-12
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值