IAdapter
IAdapter

Reputation: 64817

Unit-test framework for bean comparison

Is there any good framework for comparing whole objects?

now i do

assertEquals("[email protected]", 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.

Upvotes: 0

Views: 1094

Answers (5)

atamur
atamur

Reputation: 1577

I would go for hamcrest matchers. They allow me to write code like this:

assertThat(obj, hasProperty("email", equalTo("[email protected]")));

Upvotes: 1

IAdapter
IAdapter

Reputation: 64817

this has helped me with that How to test for equality of complex object graphs?

Upvotes: 1

Winter
Winter

Reputation: 1490

You can also implement the comparable interface.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html

Upvotes: 1

Sam Holder
Sam Holder

Reputation: 32954

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("[email protected]", 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 "[email protected]".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.

Upvotes: 1

Paul McKenzie
Paul McKenzie

Reputation: 20094

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

Upvotes: 0

Related Questions