After writing unit tests for awhile, you will observe there are common patterns and common needs. One way to fulfill some of these needs is to use a “test base class” or an “abstract test class”. Using such a pattern for MSTest can help you create more robust unit tests with less code.
The concept is pretty straight forward. Basically, create a base class that can perform some mundane or defensive programming tasks for you.
In MSTest, this is accomplished by create a new class (or unit test class) in either your test assembly or a common assembly (that is also a test assembly). You cannot make it truly abstract (that leads to some funkiness), but you can inherit from in when you create a new unit test class by decorating it with the TestMethod attribute.
You can push the typical TestContext property up to a base unit test class, as well as provide virtual methods for TestInitialize and TestCleanup.
Things to think about for you Test Base class:
· Mock out items and clean up all your mocking
· Clean up your dead files
· Add support methods to copy test files
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestSupport
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class TestBase
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public virtual TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
[ClassInitialize]
public static void MyClassInitialize(TestContext testContext) { }
[ClassCleanup]
public static void MyClassCleanup() { }
protected bool _testInitializedRan;
[TestInitialize]
public virtual void MyTestInitialize()
{
_testInitializedRan = true;
}
[TestCleanup]
public virtual void MyTestCleanup() { }
}
[TestClass]
public class MyTestClass : TestBase
{
[TestMethod]
public void ShowsThatTestInitializeRan()
{
Assert.IsTrue(_testInitializedRan);
}
}
}