mstest Test Categories!

NUnit and xUnit.net have more regular releases than mstest. This is understandable since they are both small, opensource projects whereas mstest is part of Visual Studio which is far from a small project and far far from an opensource one. As a result, they have more mature feature sets. As a long time mstest user, I was happy to see Visual Studio 2010 is still improving mstest. Recently mstest  introduced a useful new feature Test Categories!

TestCategoryAttribute

Often I find the need to group related tests. Maybe I want to group and run a subset of tests within a test Project. Visual Studio already supports grouping by namespace and project. When you have a cross-cutting concern such as Logging or Localization, which covers many namespaces and projects this breaks down. Enter TestCategoryAttribute. TestCategoryAttribute lets you decorate your TestMethod’s with any category name and easily search and run only those tests!

Sample Code:


public class Person
{
    public int Age { get; set; }

    public string Name { get; set; }

    public string Says(string something)
    {
        if (something == null) throw new ArgumentNullException("something");

        return something;
    }
}

[TestClass]
public class PersonTest
{
    Person _person;

    [TestInitialize]
    public void Init()
    {
        _person = new Person();
    }

    [TestMethod]
    [TestCategory("Method")]
    public void Says_HelloWorld_ReturnsHelloWorld()
    {
        const string helloWorld = "Hello World";

        string actual = _person.Says(helloWorld);

        Assert.AreEqual(helloWorld, actual);
    }
}

Filtering the tests:

Select the Test View, then Test Categories and enter the category name! In the sample I created a ‘Method’ category to separate my method tests from property tests… it’s not a great example of when to use Categories, but it demonstrates how they work.

Advertisements
This entry was posted in C#, Unit Testing and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s