我不想创建在dto字段时处理执行的单元测试!=实体字段



我想创建单元测试,当dto字段=实体字段时处理异常。并打印缺失和额外的字段。是否有可能使它与MapStruct?

没有注释和样板代码的简单示例。我有

public class TestDto {
long id;
String name;
int age;
long customerId;
String phone;
}

和实体

public class TestEntity {
long id;
String name;
int age;
Customer customer;
String address;
}
@Mapping(source = "person.id", target = "personId") // in my Mapper class
TestDto toDto(Test entity);

output: dto缺少字段。请添加!:地址;dto的额外字段。请删除!:电话;

我试图使用反射,但它不起作用。https://stackoverflow.com/questions/75082277/how-to-find-all-missing-and-extra-fields-in-dto-by-their-entity-using-reflec?noredirect=1 comment132500771_75082277

我很想听听关于如何做到这一点的任何想法。

Mapstruct本身不能这样做,因为它运行编译时。但是,如果您已经完全填充了对象,则可以使用生成的代码来检查这一点。

简单地将一个完全填充的dto映射到一个实体,然后再映射回dto对象。现在将生成的dto与原始dto进行比较,您可以找出哪些字段不再相同了。

通过将一个完全填充的实体映射到dto并返回到实体,对其重复此操作,您已经覆盖了实体类。

在代码中看起来像这样:

@Test
void dtoFieldTest() {
TestDto original = createFilledTestDto();
TestMapper testMapper = TestMapper.INSTANCE;

TestDto result = testMapper.mapEntityToDto(testMapper.mapDtoToEntity(original));
// assertj assertions
assertThat(result).isEqualTo(original);
// or if you cannot use the dto equals method.
assertThat(result).usingRecursiveComparison().isEqualTo(original);
}