【问题标题】:How to compare two complex object and ignore both null and empty string?如何比较两个复杂对象并忽略空字符串和空字符串?
【发布时间】:2016-07-19 12:40:11
【问题描述】:

我需要断言两个复杂对象,其中可能包含原始对象和 n 级对象。所以我用谷歌搜索并选择了一个图书馆unitils。但我有条件需要将空字符串和空字符串视为相等。但这里它只支持ReflectionComparatorMode.IGNORE_DEFAULTS。 场景:

 public class AssertVerify {

    public static void main(String args[]){

    CustomerPojo cuPojo1=new CustomerPojo();
    CustomerPojo cuPojo2=new CustomerPojo();

    cuPojo1.setCustomerName("obuli");
    cuPojo1.setCustomerAge("20");
    cuPojo1.setAddress("");

    cuPojo2.setCustomerName("obuli");
    cuPojo2.setCustomerAge("20");


    /**
     * Asserting  two pojos
     */     
    ReflectionAssert.assertReflectionEquals(cuPojo1, cuPojo2,
            ReflectionComparatorMode.LENIENT_DATES ,ReflectionComparatorMode.IGNORE_DEFAULTS);

}       

错误:

 junit.framework.AssertionFailedError: 
 Expected: CustomerPojo<customerName="obuli", customerAge="20", Address="">
  Actual: CustomerPojo<customerName="obuli", customerAge="20", Address=null>

  --- Found following differences ---
  Address: expected: "", actual: null

   --- Difference detail tree ---
  expected: CustomerPojo<customerName="obuli", customerAge="20", Address="">
   actual: CustomerPojo<customerName="obuli", customerAge="20",   Address=null>

  Address expected: ""
  Address   actual: null


   at junit.framework.Assert.fail(Assert.java:47)
    at      org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals(ReflectionA   ssert.java:136)at       org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals(ReflectionA   ssert.java:99)
atcom.assertion.verify.AssertVerify.main(AssertVerify.java:52) 

 picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true

我需要添加一个规则,将 null 和空字符串视为相等。

对于我的情况有什么可能的解决方案吗?

【问题讨论】:

  • 为什么不直接实现可比较接口并编写自己的equals方法?

标签: java assert unitils object-comparison


【解决方案1】:

正如 Gremash 所提到的,你应该实现 comparable 接口并覆盖 equals 方法,不要着急,确保你知道你在做什么,因为当你使用你自己的实现这个的对象时,你可能会弄乱集合中的工作接口并使用你的方法。看一看(如果可能的话)在 Core Java 1-2 系列中,这些书中讨论了这个问题并详细解释了。 有一些规则,例如 equals() 必须定义一个等价关系(它必须是自反的、对称的和传递的),更多的是:What issues should be considered when overriding equals and hashCode in Java?

我认为最好还是走这条路然后再依赖其他库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    相关资源
    最近更新 更多