Thursday, 16 May 2013

Mulitple Assertions in one test

https://gist.github.com/DominicFinn/5441803#file-multipleassertions-cs

This might be a bit of an anti-pattern to some but I have found it's sometimes useful to test more than one assertion in a test. Some would say, one assertion per test and yes this is normally the case. But sometimes you want to just check that all the values on a form have been bound to a model or all the values have been saved to an object correctly. In this case, one assertion per test is just a gigantic bit of ceremony. All you really want to express is that the model is bound so you can call the method TheModelIsBoundCorrectly() and not TheDateIsSet(), ThePostcodeIsSet(), TheNameIsSet(). Ugh that would be a pain.

The problem with putting all the assertions in the same method is that when one fails, it raises an exception. It's a real pain to have to fix the test, run it and then the next field fails too and so on. The above would run all the tests first and only throw after running them all. It will give you a summary of what went wrong too.

Above is one possible solution to the problem. As I am typing this, I wonder if it would be easier to just have an Assert.IsTrue(ModelIsBoundCorrectly(model)) and then have the method ModelIsBoundCorrecltly check the fields. I suppose my above solution offers more reuse though and the feedback it collects for the test failure is also a boon as it pinpoints what went wrong.

No comments:

Comments System

Disqus Shortname