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!
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.