简体   繁体   English

Java 比较复杂对象,不包括 JUnit 的某些字段

[英]Java Compare complex objects excluding some fields for JUnit

I tried the Unitils tool which is really great, but doesn't provide you an option for excluding fields.我尝试了 Unitils 工具,它真的很棒,但没有为您提供排除字段的选项。 The only way by doing this is setting null the objects and enable a flag "IGNORE_DEFAULTS", but in my case it's not helpful, since I've got some ids autogenerated by the system.这样做的唯一方法是将对象设置为 null 并启用标志“IGNORE_DEFAULTS”,但在我的情况下它没有帮助,因为我有一些由系统自动生成的 ID。 So if i could just add the id to an exclude list it would be perfect.因此,如果我可以将 id 添加到排除列表中,那就太完美了。

I also tried Mockito ReflectionEquals but was not helpful, since i need a field to field comparison.我也尝试过 Mockito ReflectionEquals 但没有帮助,因为我需要一个字段到字段的比较。

Is there something else helpful ?还有其他有用的东西吗? I 'm searching for hours without success.我正在寻找数小时但没有成功。

Thank you in advance!提前谢谢你!

You could solve your problem by using AssertJ .您可以使用AssertJ解决您的问题。 It can do field-by-field recursive comparison with options to ignore fields by name, regex or type.它可以使用按名称、正则表达式或类型忽略字段的选项进行逐字段递归比较

assertThat(sherlock)
  .usingRecursiveComparison()
  .ignoringFields("name", "home.address.street")
  .isEqualTo(moriarty);

如果您不喜欢所发现的功能,那么使用 Java 反射来推出自己的功能并不难。

We use our own approach in groovy (similar to Frank Neblung's answer ) where we convert an object to a formated Json string using an ObjectMapper and a filterList for the attributes.我们在 groovy 中使用我们自己的方法(类似于Frank Neblung 的回答),我们使用 ObjectMapper 和属性的 filterList 将对象转换为格式化的 Json 字符串。 This is pretty handy for testing but has also some downsides like the loss of type information.这对于测试非常方便,但也有一些缺点,例如丢失类型信息。

// interface of the conversion
String nice(Object o, String... filterList) { ... }

// test calls
assertEquals(nice(actual, ["-unusedAttribute", "-unusedAttribute2"]), nice(expected, ["-unusedAttribute", "-unusedAttribute2"]))
assertEquals(nice(actual, ["+usedAttibute", "+usedAttibute2"]), nice(expected, ["+usedAttibute", "+usedAttibute2"]))

// test calls using the spock framework
nice(actual, ["-unusedAttribute", "-unusedAttribute2"]) == nice(expected, ["-unusedAttribute", "-unusedAttribute2"])
nice(actual, ["+usedAttibute", "+usedAttibute2"]) == nice(expected, ["+usedAttibute", "+usedAttibute2"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM