views:

92

answers:

4

I have a ArticleController that displays a list of articles according to a category.

public ActionResult List(string categoryname)
{
       MyStronglyTypedViewData vd = new MyStronglyTypedViewData();

       DBFactory factory = new DBFactory();

       categoryDao = factory.GetCategoryDao();
       articleDao = factory.GetArticleDao();


       vd.Category = categoryDao.GetByName(categoryname);
       vd.Articles = articleDao.GetByCategoryId(vd.Category.Id);


       return View(vd);
}

If I was to unit test this action, what exactly would be the purpose? TO make sure the correct view is being opened?

+7  A: 
  1. Make sure that a ViewResult is returned
  2. Make sure the view result has a model
  3. Make sure this model is not null and is of type MyStronglyTypedViewData
  4. Assert properties on the model

This line DBFactory factory = new DBFactory(); makes me think that it would be difficult to write a unit test because you don't use an interface that could be mocked, but rather rely on a concrete class which might hit the actual database.

Darin Dimitrov
+2  A: 

Consider also error cases: categoryname is a string from the web. How should the action behave if the user passed a "bad" one? Looks to me like you might get a null reference error?

It's as important to test error cases as functional cases.

Craig Stuntz
+1  A: 

Test various edge cases in the objects returned by categoryDao.GetByName(categoryname); and articleDao.GetByCategoryId(vd.Category.Id); Test what happens when they throw exceptions

Also, if you believe your design could be better if it adhered to the Dependency Inversion Principle (I'm just saying "if"; whether you should believe that is a separate question), then trying to write a well-isolated unit test for your method and to break the dependencies could be a useful exercise leading to an improved design of your program.

azheglov
A: 

This is what our team concluded as what must be verified (we use BDD) for each controller:

  • Verify every action returns the correct view name.
    • Verify that each ViewName is appropriately triggered and returned if the action can return multiple views.
    • Verify ViewData returned is fully populated and type correct.
  • Verify controller bubbles up correct exceptions.
    • Verify all RuleViolations bubbled up from the service/model is contained in the ViewData. (this goes beyond just data constraint violations in the Request)
Jason