How do I assert equality on two classes without an equals method?

后端 未结 23 1664
臣服心动
臣服心动 2020-11-28 05:20

Say I have a class with no equals() method, to which do not have the source. I want to assert equality on two instances of that class.

I can do multiple asserts:

23条回答
  •  醉酒成梦
    2020-11-28 05:54

    I had the exact same conundrum when unit testing an Android app, and the easiest solution I came up with was simply to use Gson to convert my actual and expected value objects into json and compare them as strings.

    String actual = new Gson().toJson( myObj.getValues() );
    String expected = new Gson().toJson( new MyValues(true,1) );
    
    assertEquals(expected, actual);
    

    The advantages of this over manually comparing field-by-field is that you compare all your fields, so even if you later on add a new field to your class it will get automatically tested, as compared to if you were using a bunch of assertEquals() on all the fields, which would then need to be updated if you add more fields to your class.

    jUnit also displays the strings for you so you can directly see where they differ. Not sure how reliable the field ordering by Gson is though, that could be a potential problem.

提交回复
热议问题