Thursday, March 31, 2011

Using a base class for unit test setup and teardown

Assuming Visual Studio.NET 2008 and MsTest are used to run unit tests. When a system is based on a service container and dependency injection unit testing would naturally require the setting up of services.

Should these services rather be setup in a base class that all unit tests derive from or in each unit test class. If they should be in a base class, is there a way to have the TestInitialize and ClassInitialize methods be executed without requiring them to be called from the derived class, e.g base.Initialise?

From stackoverflow
  • I prefer the Test* and Class* marked methods to be on the actual unit test class. If you define them on a base class, you cannot add test specific activities to them. Instead, use the static and instance constructors and finalizer on your base class.

  • The MSTest framework will search the entire object (all base classes) for the methods marked Test*. Like when you declare them on the unit test class, you do not have to call them explicitly.

    sduplooy : Class* methods will always be marked as static and hence will not be called from derived classes. The Test* methods will be called since they are instance methods.
    Anthony Mastrean : You're right, fixed the answer.
  • With 2008, you should be able to have [TestInitialize] on a base class, and as long as you don't add another [TestInitialize] somewhere down the hierarchy, it should be called. You could also do things with virtual methods.

0 comments:

Post a Comment