如何在EqualsVerifier中忽略Thing类的complexObject属性?
解决方法
1. 修改当前测试(最简单的局部方案)
在你的ThingTest里,给EqualsVerifier加上忽略字段的配置,直接跳过complexObject的检查,这样就不用管ComplexType能不能实例化了:
class ThingTest { @Test fun `test equals and hashCode`() { EqualsVerifier.forClass(Thing::class.java) .withIgnoredFields("complexObject") .verify() } }
或者因为你的equals方法本来就只用到name,也可以直接指定只检查这个字段,效果一样:
EqualsVerifier.forClass(Thing::class.java) .withOnlyTheseFields("name") .verify()
2. 全局配置(不用改下游测试)
如果下游测试里也有用到EqualsVerifier测试包含Thing的类,不想让每个测试都手动加忽略规则,可以全局配置EqualsVerifier,把Thing的忽略规则一次性设置好。
你可以在测试模块的基类或者初始化代码里加这段配置,比如用JUnit的@BeforeClass注解让它在所有测试前执行:
import nl.jqno.equalsverifier.EqualsVerifier class TestBase { companion object { @JvmStatic @BeforeClass fun setupEqualsVerifier() { EqualsVerifier.configure() .forClass(Thing::class.java) .withIgnoredFields("complexObject") .andDoNotVerify() } } }
之后所有测试只要继承这个基类,EqualsVerifier就会自动忽略Thing的complexObject字段,下游测试完全不用改。
3. 类注解方案(EqualsVerifier 3.10+可用)
如果你的EqualsVerifier版本够新(3.10及以上),可以直接在Thing类上加注解,全局生效:
import nl.jqno.equalsverifier.annotation.EqualsVerifierIgnoredFields @EqualsVerifierIgnoredFields("complexObject") class Thing(val name: String) { internal var complexObject: ComplexType? = null override fun equals(other: Any?): Boolean { return other is Thing && name == other.name } }
这样不管是你的测试还是下游测试,只要用EqualsVerifier处理Thing,都会自动跳过这个字段的检查,完全不需要修改任何测试代码。
内容的提问来源于stack exchange,提问作者Felix Dombek
相关产品推荐
相关产品推荐

