Earlier this year, I shared my set of fluent assertion extension methods for xUnit. Here's a neat update which comes in handy whenever you´re doing assertions on things like anonymous objects – for example the data of a JsonResult from an ASP.NET MVC controller action:
return Json(new { status = "ok"})
Aside: You may balk at this and say we really should have a DTO instead of using anonymous object notation here – and you may be right. But lets disregard that for the rest of this post… :)
Normally, to write a test which verifies that the JsonResult's Data property indeed contains a status property with the value “ok”, we would need to crack it open with reflection:
[Observation]
public void Status_is_ok()
{
var json = (JsonResult) _result;
PropertyInfo statusProperty = json.Data.GetType().GetProperty("status");
Assert.NotNull(statusProperty);
statusProperty.GetValue(json.Data, null).ShouldBeEqualTo("ok");
}
That looks pretty ugly and unreadable, I think. So I've packed the ugliness away into a new helper method for my fluent assertion library, allowing me to write the above much more readably:
[Observation]
public void Status_is_ok()
{
var json = (JsonResult) _result;
json.Data.ShouldHaveProperty("status")
.Value
.ShouldBeOfType<string>()
.ShouldBeEqualTo("ok");
}
Notice also that I've now made it possible to chain assertions together, since the Should methods now return the object being asserted on.
You can download the updated assertion extension methods here