views:

206

answers:

3

Is there anything wrong with checking so many things in this unit test?:

ActualModel = ActualResult.AssertViewRendered()        // check 1
                          .ForView("Index")            // check 2
                          .WithViewData<List<Page>>(); // check 3

CollectionAssert.AreEqual(Expected, ActualModel);      // check 4

The primary goals of this test are to verify the right view is returned (check 2) and it contains the right data (check 4).

Would I gain anything by splitting this into multiple tests? I'm all about doing things right, but I'm not going to split things up if it doesn't have practical value.

I'm pretty new to unit testing, so be gentle.

+1  A: 

It's best to stick with only one assert in each test to avoid Assertion Roulette.

If you need to set up the same scenario to test multiple conditions based on identical premises, it's better to extract the setup code to a shared helper method, and then write several tests that call this helper method.

This ensures that each test case tests only one thing.

As always, there are exceptions to this rule, but since you are new to unit testing, I would recommend that you stick with the one assertion per unit test rule until you have learned when it's okay to deviate.

Mark Seemann
That makes sense. thanks!
Michael Haren
+2  A: 

As long as each assertion has a unique and identifying failure message you should be good and will sidestep any Assertion Roulette issues because it won't be hard to tell which test failed. Use common sense.

John K
The problem with having multiple asserts isn't with telling which one failed - in most cases you get the line number, if nothing else. The problem is that you don't get to see if later tests would also fail, so you end up with less information about the bug. In some cases this isn't significant - but in some (most, in my experience, before I learnt this lesson) it is.
Bevan
+2  A: 

As others have pointed out, it's best to stick with one assert in each test in order to avoid losing information - if the first assert fails, you don't know whether the later ones would fail also. You have to fix the problem with less information - which might (probably will) be harder.

A very good reference is Roy Osherove's Art of Unit Testing - if you want to get started right with Unit Testing, you could do a lot worse than starting here.

Bevan
I found that book very good. It improved the quality of my unit tests tremendously. And while most books on software development are very thick, this book contains about 270 pages. This makes it great to put on your team's must-read list. And if you're in a hurry, Roy advices you to read only chapter 7.
Steven