sduplooy
sduplooy

Reputation: 14720

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?

Upvotes: 12

Views: 4861

Answers (3)

Dominic Hopton
Dominic Hopton

Reputation: 7292

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.

Upvotes: 6

Anthony Mastrean
Anthony Mastrean

Reputation: 22394

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.

Upvotes: 8

Anthony Mastrean
Anthony Mastrean

Reputation: 22394

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.

Upvotes: 0

Related Questions