No Slow Unit Tests with xUnit.net

Monday, July 21, 2008 – 5:00 AM

Ever discovered people on your team have gotten into the habit of writing slow unit tests? Tests that take half a minute to execute, that bog down both your development and your build server?

With xUnit.net you can extend the Fact attribute to set the test timeout. In the example below the new StrictFact attribute will fail any test that takes longer than a second.

  using System.Threading;
  using Xunit;

  namespace Application.Tests
  {
    public class MyTests
    {
      [StrictFact]
      public void MyFailingTest()
      {
        Thread.Sleep(2000);
      }
    }

    public class StrictFactAttribute : FactAttribute
    {
      public StrictFactAttribute()
      {
        base.Timeout = 1000;
      }
    }
  }

Now all you have to do is periodically check the code for Fact attributes. You can do this with a simple MSBuild task or an NDepend static analysis rule to search for instances of the basic Fact attribute and treat them as an error.

You can do something similar with NUnit and MSTest but its not as clean as you have to define initialize and cleanup methods to track the time for each test. The Test Driven Developer explains how. This will probably result in a common base class for al your tests which I’d consider to be an anti-pattern.