Why you should test code too silly to break
I wrote a test for this piece code:
public virtual void View([ARFetch("id")]Webcast webcast) { PropertyBag["webcast"] = webcast; }
Now, this looks like utter lunacy, isn't it? Especially when the test looks like:
[Test] public void When_view_called_will_send_webcast_to_view() { var webcast = new Webcast(); controller.View(webcast); controller.PropertyBag["webcast"].ShouldBeTheSameAs(webcast); }
Except that now that I have covered the very basic item, I now have another few tests:
[Test] public void When_view_called_with_null_webcast_will_render_missing_webcast_view() { controller.View(null); controller.SelectedViewName.ShouldEqual(@"Webcast\Missing"); } [Test] public void When_view_called_with_unpublished_webcast_will_render_unpublished_webcast_view() { controller.View(new Webcast()); controller.SelectedViewName.ShouldEqual(@"Webcast\Unpublished"); }
And the simplest thing that can make those test pass is:
public virtual void View([ARFetch("id")]Webcast webcast) { if(webcast==null) { RenderView("Missing"); return; } if(webcast.PublishDate==null) { RenderView("Unpublished"); return; } PropertyBag["webcast"] = webcast; }
By having tests from the beginning, even for trivial piece of code, I ensured both that the trivial case will work and that I am already starting with the right tone.
Comments
If that's silly, then I guess I do silly things too. Confirming items get populated in the property bag or the correct view gets selected is actually relevant IMO, especially when it comes time to refactor/change the controller. My tests like that have saved me before, especially when you consider the cost of writing the tests is really low.
@Ayende
"I wrote a test for this piece [of] code:"
If you wrote test first there would be no question.
These lines of code are not siily as they implement some "behaviour" ... or desired features. I agree they have a very low risk to break... unless a full rewrite which has a higher risk to occur :-)
Comment preview