The correct way to compare an object in Unit test

I am writing unit tests for my grails application, and I realized that I do not know how to correctly determine whether an object is a suitable object or not.

For example, given this test:

void testExampleTest() {
    mockSession.person = new Person(firstName:'John', lastName:'Doe', middleInitial:'E')
    def model = controller.testMethod()
    ...assertions...
}

and

def testMethod = {
    Person currPerson = session.getAttribute("person")
    render(view:'view',model:[person:currPerson]
}

How should I make sure that the person object that I added to the session is correctly passed in the model? Is it enough to use

assertEquals( person,model['person'] )

or because I myself entered the object into the session, it makes sense to use

assertEquals( person.firstName, model['person'].firstName )
assertEquals( person.lastName, model['person'].lastName )
assertequals( person.middleName, model['person'].middleName )

It seems to me that the first path should be sufficient if the object has a correctly defined equals method, but I just wanted to see what the usual way is.

thank

+5
source share
8 answers

- , , XUnitPatterns, equals().

, personEquals() Person.equals() . , , . , assertEquals(), .

+2

, . ,

, , ", ", .

, , equals.

, , .

+2

, property by property , - , -

+2

equals , . , , , unit test, equals ( , , ).

, Person. , , , . , . , ( ).

+1

- , . , , , model['person'] - , , , person:

assertSame(person, model['person'])

Hamcrest, :

assertThat(model['person'], sameInstance(person))
+1

, equals, . "" , , .

, ID. , , . , , :

assertEqualProperties(person, model['person'], "firstName", "lastName", "middleName");

( , commons- beans). Groovy, , , . non-equal .

0

Grails , XML-:

public void compareXML(Object a, Object b)
    ByteArrayOutputStream aBaos = new ByteArrayOutputStream();
    XMLEncoder aEncoder = new XMLEncoder(aBaos);
    aEncoder.writeObject(a);
    aEncoder.close();
    String xmlA = baos.toString();

    ByteArrayOutputStream bBaos = new ByteArrayOutputStream();
    XMLEncoder bEncoder = new XMLEncoder(bBaos);
    bEncoder.writeObject(b);
    bEncoder.close();
    String xmlB = bBaos.toString();

    assertEquals(xmlA, xmlB);
}

eclipse, XML, .

0

assertSame(). - , - , , .

0

All Articles