Asserting for equality anonymous types

I faced a problem asserting two anonymous types.

What I've done so far

  • I have unit test project which sees the internals of my project under test, so anonymous types are visible to test project.
  • I've read about anonymous types behaving more like structures(value types) rather than reference types here: Why anonymous types Equals implementation compares fields?

Yet again, while trying to test again equality following assertion exceptions occur:

1.

Assert.IsTrue(actionResult.Value.Equals(expectedActionResult.Value));

Expected: True But was: False

2.

Assert.AreEqual(actionResult.Value, expectedActionResult.Value);

Expected: <{ errorCode = -4, errorMessage = Invalid or Missing parameters within the request. }> (<>f__AnonymousType0'2[System.Int32,System.String]) But was: <{ errorCode = -4, errorMessage = Invalid or Missing parameters within the request. }> (<>f__AnonymousType0'2[System.Int32,System.String])

This is where I create real and expected result:

var actionResult = _systemUnderTest.GetToken(null) as JsonResult;
var expectedActionResult = 
    new JsonResult(new
    {
        errorCode = (int)ErrorCodes.InvalidOrMissingParameters, errorMessage = ErrorCodes.InvalidOrMissingParameters.GetDescription()
    });

What am I missing?

Jon Skeet
people
quotationmark

Even though the anonymous types are accessible in your test project, that doesn't mean they'll be used when you write new { ... }.

If you look at actionResult.Value.GetType() and expectedActionResult.Value.GetType() I strongly suspect you'll see that they're different types from different assemblies.

The simplest workaround in this case is probably just to compare the resulting JSON instead.

people

See more on this question at Stackoverflow