1

I need to assert two complex objects which may contains both primitive and n levels of objects within. so i googled and chose a library unitils. But i have condition that i need to consider both the null and empty string as equal.But here it only supports ReflectionComparatorMode.IGNORE_DEFAULTS. Scenario:

 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);

}       

Error:

 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

I need to add an rule that consider both null and empty string as equal.

Is there is any possible solution available for my situation.

Obuli Sundar
  • 566
  • 7
  • 26

1 Answers1

-1

As was mentioned by Gremash you shoud implement comparable interface and override equals method , dont rush this , make sure you know what you doing since you can mess up work in collections when you use your own objects that implement this interface and use your method.Take a look(if possible) at Core Java 1-2 series this problematic is discussed in these books and detaily explained. There are some rules for instance equals() must define an equivalence relation (it must be reflexive, symmetric, and transitive), more on that : What issues should be considered when overriding equals and hashCode in Java?

I think its still better to go this way then rely on other library.

Community
  • 1
  • 1
Tomas Bisciak
  • 2,801
  • 5
  • 33
  • 57
  • Test case issues should not cause changes in prod code. Overriding equals ar adding Comparable changes the intent of the class, could change behavior and may introduce unwanted dependency later by other developers. – Daniel Hári Jun 15 '23 at 21:36