如何正确地对可打包对象进行单元测试?

How to properly unit test parcelable objects?

我想知道单元测试 Android 可打包对象的最佳方法是什么。我知道如何使用 Parcel.obtain() 测试可打包对象并将其写入包裹并使用创建者创建它。这种方法的问题在于,如果有人将字段添加到对象而不将其添加到 parcelable/equals/hashcode 逻辑中,它将无法捕获。是否存在用于确认所有对象字段都已写入包裹的库或方法?我知道并不是所有的字段都应该被打包,我设想一个注释或每个字段的东西来确定是否应该包含在单元测试中。

您可以使用EqualsBuilder.reflectionEquals from Apache Commons Lang

在你的build.gradle中:

testCompile 'org.apache.commons:commons-lang3:3.4'

然后您可以指定忽略哪些字段或使其忽略 transient 个字段

User one = new User();
one.setName("Salem")
one.setLastName("Saberhagen");
one.setAddress("Somewhere");
one.setAge(1000);

User two = one.clone();
two.setAddress("Mars");
two.setAge(2000);

reflectionEquals(one, two); // -> False
reflectionEquals(one, two, "address", "age"); // -> True