【问题标题】:How to properly unit test parcelable objects?如何正确对可打包对象进行单元测试?
【发布时间】:2023-03-20 05:47:02
【问题描述】:

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

【问题讨论】:

    标签: java android unit-testing junit


    【解决方案1】:

    你可以从Apache Commons Lang使用EqualsBuilder.reflectionEquals

    在你的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-11
      • 2021-12-22
      • 2010-09-23
      • 2014-01-30
      • 2011-02-02
      • 1970-01-01
      相关资源
      最近更新 更多