views:

39

answers:

2

Today I finally started to write some unit tests for my new ASP.net MVC project seriously. Some unit tests, however, kept returning for every action in a each controller:

  • Perform a test whether the returned ActionResult is not null.
  • Perform a test whether the action returns a valid ActionResult if the ModelState is invalid.
  • Perform a test if the type of ActionResult matches a certain type (e.g. ViewResult or RedirectResult).

These three tests contained more or less the same code for every action. Since I like to avoid duplicate code, I thought of automating these 'default' kind of tests for every action. I did some quick Googles about it, but couldn't find anything.

So:

  • Is automating default test a wise thing to do?
  • If yes, any scripts available or persons who already did something like this before?
  • If no one did something before, any suggestions on how to approach this?

Thanks for any replies!

+1  A: 

I don think that having similar tests for different controllers is 'duplicate' code. The testing logic should be refactored so that it can be re-used. Re-used test code to test different controllers thus is not duplication.

Have you looked at the TestHelpers within MvcContrib. I would think that alot of the common controller type tests have already been implemented. There are also other aspects that make testing a bit easier. That been said, it can used to set up your tests more easily. Have a look at this answer regarding Unit Testing Overkill.

Ahmad
Nice pointers in the right direction. Obviously not the idea I had, but MvcContrib together with the other answer about not getting too complex test code, will give me an idea how to approach writing the rest of the unit tests. Thanks!
Monty
Maybe the simplest solution is to write some snippets in Visual Studio to quickly write the default tests.
Monty
+1  A: 

First big tactical question is "what unit testing stack are you using?" Some [mstest] don't support inheritance in tests so doing this sort of thing is tricky.

As for actually doing it, I've generally found that this might make sense but having too much shared code in unit tests can be a bad thing -- what happens when your unit test codes gets so complex that you need unit tests for the test code?

Wyatt Barnett
Good comment, thanks! Didn't thought through of too complex unit test code. At this moment, I indeed use mstest.
Monty
Well, mstest is your first problem here :)
Wyatt Barnett