Excluding Integration and other tests when running Unit Tests locally in Visual Studio

Often, a solution may have both Unit Tests and Integration Tests. Unit Tests should be highly specific, and should be testing one class object. Integration Test could be vastly more complex and could use Selenium, or require a real database server, etc. Even if a solution doesn’t have Integration Tests, it may have slow Unit Tests. For example, I have a test that takes about 2 minutes to run because it is testing that when creating 10 million random strings, the character distribution is pretty equal.

I don’t want to either slow Unit Tests or Integration Tests to run every single time I build on my local dev box. I do have an automated build system and builds kick off on check-in. At that time, these slow tests will run every time. But locally, it is just an unnecessary delay.

Usually I am writing in a specific project and that project has specific tests and I can easily choose to only run tests in my current project. But what if I am updating a library that many projects use. I want to know quickly if anything is broke, so I need to run most of the tests in the entire solution.

Visual Studio allows for tests to be tagged with a TestCategoryAttribute.

You can mark different tests with different names: [TestCategory(“Slow”)], [TestCategory(“Integration”)], [TestCategory(“Performance”)], [TestCategory(“Selenium”)]

Example:

[TestMethod]
[TestCategory("Slow")]
public void TestDistributionInTenMillionCharacters()
{
    // some code here
}

All other tests are left without a test category. Now, if you want to run all tests that aren’t slow, you can do this in Visual Studio Test Explorer by grouping tests using the “Traits” selection option.

Once you have marked all tests with an appropriate TestCategoryAttribute, you can sort by Trait. Now it is simple to click-to-highlight the No Traits group and click Run | Selected Tests.

Leave a Reply

How to post code in comments?