Unit-test framework for bean comparison
Is there any good framework f开发者_高级运维or comparing whole objects?
now i do
assertEquals("ha@gmail.com", obj.email);
assertEquals("5", obj.shop);
if bad email is returned i never get to know if it had the right shop, i would like to get a list of incorrect fields.
Going with the 1 test, 1 assert line of thinking if you has each assert in its own test you would know if one or both of these had failed by the fact that there were 1 or 2 failing tests.
@Test
public void TestEmail()
{
obj = GetTestObject();
assertEquals("ha@gmail.com", obj.email);
}
@Test
public void TestShop()
{
obj = GetTestObject();
assertEquals("5", obj.shop);
}
obviously you need to move the setup of the object into a method ot have it performed in the test set up method and have it a class variable.
If you actually want to test if all properties are set in a single test:
@Test
public void TestAllProperties()
{
obj = GetTestObject();
bool testResult=true;
string failureString;
if "ha@gmail.com".equals( obj.email) == false
{
testResult=false;
failureString+="email was different";
}
if "5".equals( obj.shop) == false
{
testResult=false;
failureString+="shop was different";
}
assertTrue(testResult,failurestring);
}
but I'm not sure what this gives you really.
But if you really want to compare the whole objects equality then override the equals method (not forgetting getHashCode too) and do your equality checking in there. after all that is what it is for...
If you want a list of incorrect fields you could make the equals method populate an internal list which you could query if the equality check failed, to get the list of failed fields the last time equality was checked. Don't really think that's a good idea though.
You can also implement the comparable interface.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html
this has helped me with that How to test for equality of complex object graphs?
I would go for hamcrest matchers. They allow me to write code like this:
assertThat(obj, hasProperty("email", equalTo("ha@gmail.com")));
If you want to test object equality, then surely you need to implement equals() and test using assertEquals(), but otherwise Sam is correct, one assertion per test
精彩评论