you can try catching ComparisonFailure exception like below
P.S Run one assert at a time i.e. comment another to see which exception is caught
@org.junit.Test
public void someSimpleTest() {
try {
Assert.assertEquals("123", "456");//Throw ComparisonFailure
Assert.assertArrayEquals(new String[] {"ABC","efg"}, new String[] {"ABCe","xys"});//Throw ArrayComparisonFailure
} catch(ComparisonFailure e) {
System.out.println("Inside block");
System.out.println(e);
} catch(ArrayComparisonFailure e) {
System.out.println("Inside block");
System.out.println(e);
}
}
in this example, If I comment the seertEquals and execute assertArrayEquals, It will clearly print the statement
arrays first differed at element [0]; expected:<ABC[]> but was:<ABC[e]>
Hence to answer your question Is there any way in JUnit, to directly specify if which property of expected object did not match that of actual object?
This clearly states the first element are not equal hence it failed.
Similarly, you can check for your toString differences.
http://junit.sourceforge.net/javadoc/org/junit/ComparisonFailure.html
Update For custom object
This code will only print the difference between the toString of the Object
class PojoClass {
String prop1;
int prop2;
String prop3;
public PojoClass(String prop1, int prop2, String prop3) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PojoClass other = (PojoClass) obj;
if (prop1 == null) {
if (other.prop1 != null)
return false;
} else if (!prop1.equals(other.prop1))
return false;
if (prop2 != other.prop2)
return false;
if (prop3 == null) {
if (other.prop3 != null)
return false;
} else if (!prop3.equals(other.prop3))
return false;
return true;
}
@Override
public String toString() {
return "PojoClass [prop1=" + prop1 + ", prop2=" + prop2 + ", prop3=" + prop3 + "]";
}
Junit to print the assertion error difference
@org.junit.Test
public void someSimpleTest() {
try {
PojoClass class1 = new PojoClass("Sample", 1, "foo");
PojoClass class2 = new PojoClass("Sample1", 1, "foo2");
Assert.assertEquals(class1, class2);
} catch(AssertionError e) {
getStringDiff(e);
}
}
private void getStringDiff(AssertionError e) {
String msg = e.getMessage();
String str1 = msg.substring(msg.indexOf("<"), msg.indexOf(">")+1);
String str2 = msg.substring(msg.lastIndexOf("<"), msg.lastIndexOf(">")+1);
System.out.println(StringUtils.difference(str1, str2));
}