Today I came across Shouldly, as I followed a link in a tweet by Rob Conery. I have a thing for nifty mini-projects, so I immediately git clone http://github.com/shouldly/shouldly.git’d it, and pulled it into a small thing I am building.
What is Shouldly? Basically, it’s just a niftier way of writing assert statements in tests. It fits right in between NUnit and Rhino Mocks, so you will get the most out of it if you are using those two for your unit tests. Check out this repository test – first, arrange and act:
1 2 3 4 5 |
var notes = new Notes{Artist="Josh Rouse", Title="Winter In The Hamptons"}; repo.Save(notes); var id = notes.Id; var loadedNotes = repo.FindOne(id); |
and then, usually the assert would look something like this:
1 2 |
Assert.AreEqual("Joe Rouse", loadedNotes.Artist); Assert.AreEqual("Winter In The Hamptons", loadedNotes.Title); |
– yielding error messages like this:
1 2 3 4 |
NUnit.Framework.AssertionException: Expected string length 9 but was 10. Strings differ at index 2. Expected: "Joe Rouse" But was: "Josh Rouse" -------------^ |
which is probably OK and acceptable, because how would NUnit know any better than that?
Check out what Shouldly can do:
1 2 |
loadedNotes.Artist.ShouldBe("Joe Rouse"); loadedNotes.Title.ShouldBe("Winter In The Hamptons"); |
– yielding error messages like this:
1 2 3 4 5 |
NUnit.Framework.AssertionException: loadedNotes.Artist should be "Joe Rouse" but was "Josh Rouse" |
which IMO is just too nifty to ignore!
Shouldly takes advantage of the fact the the current StackTrace has all the information we’re after when the assert is an extension method, which is extremely cool and well thought out.
Moreover, it integrates with Rhino Mocks, yielding better messages when doing AssertWasCalled stuff: Instead of just telling that the test did not pass, it tells you exactly which calls were recorded and which one was expected – a thing that Rhino Mocks has always been missing.
Conclusion: YourNextProject.ShouldContain("Shouldly")