0

我需要断言两个复杂对象,其中可能包含原始对象和 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

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

对于我的情况,是否有任何可能的解决方案。

4

1 回答 1

0

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

我认为最好还是这样走然后依靠其他图书馆。

于 2016-03-31T11:15:24.430 回答