Fluent Reflection-Based Assertions

An entry about tdd | c# 3.0 Publication date 10. March 2009 11:57

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

Currently rated 3.0 by 6 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS