Skip to content

Deep expectations

Davyd McColl edited this page Oct 14, 2017 · 2 revisions

Often, I've needed to test that a complex object (eg one retrieved via an ORM from a database) contains the same data as a reference one. Obviously, this doesn't help:

Expect(dbPerson).To.Equal(refPerson);

Since dbPerson and refPerson have different references and .To.Equal will do a reference comparison between them.

One might be tempted to test all of the properties:

Expect(dbPerson.Id).To.Equal(refPerson.Id);
Expect(dbPerson.Name).To.Equal(refPerson.Name);
Expect(dbPerson.DateOfBirth).To.Equal(refPerson.DateOfBirth);
// and so on

But this is really inconvenient. NExpect has deep equality checking built in:

Expect(dbPerson).To.Deep.Equal(refPerson);

In addition, one might only be interested in some of the properties, in which case, Intersection equality becomes useful:

Expect(dbPerson).To.Intersection.Equal(new {
  Name = "Douglas Adams",
  DateOfBirth = new DateTime(1952, 3, 11)
});

In the test above, the Id was probably db-generated, so not really important.

Deep and Intersection equality tests allow testing disparate types, so you could have also done the Deep equality testing like so:

Expect(dbPerson).To.Deep.Equal(new {
  Id = 42,
  Name = "Douglas Adams",
  DateOfBirth = new DateTime(1952, 3, 11)
});