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")
Very nice! I’ve always hated the Assert.AreEqual(…) syntax. The main issue with the AreEqual syntax, is the parameter order confusion. Over the last year or so, I’ve switched to the Assert.That(…) syntax. But this looks way more promising. Good find, mookid.
Yeah, I agree that Assert.AreEqual(…) is sub-optimal, but I think the Assert.That(…) syntax is clunky and awkward to type. Fluent interfaces are seldomly good to speed-type.
I use NUnitEx for the same thing and have for a while:
http://code.google.com/p/nunitex/
Oh yeah, Fabio Maulo used to tweet a lot about SharpTestsEx, but I never got interested in that one.
The interesting part is IMO not about having extension methods to improve readability, it’s about having better error messages when assertions fail. Does NUnitEx/SharpTestsEx provide that as well? Can’t seem to find any information about that.