Guillermo Oramas R.
Guillermo Oramas R.

Reputation: 1303

Unit testing a static class (Theoretical Question)

I know when it is ok to use a static class, but my simple question is:

Is there a big problem when we're unit-testing our code that has a static class?

Is better to use a regular instance class?

There are some questions that talk about this, but all are based in particular cases.

Upvotes: 0

Views: 152

Answers (1)

Tim Barrass
Tim Barrass

Reputation: 4939

What I do is take the existing static class use as a seam, and provide an alternative implementation in a different namespace. This means that you can get the code under test with as few changes as possible -- just namespace changes. Typically I've had to do this to get round C# filesystem ops -- File.Exists etc.

Say your method basically does this:

using System.IO;

public void SomeMethod()
{
    ...
    if(File.Exists(myFile))
    {
        ...
    }
    ...
}

then I'd replace that implementation of File with an alternative. The alterntive implementation should stub out any existing methods, and make calls to delegate implementations under the covers -- e.g.

namespace IO.Abstractions 
{     
    public static class File
    {         
        public static Func<string, string, string> ExistsImpl =
                                                      System.IO.File.Exists;

        public static string Exists(string path)
        {             
            return ExistsImpl (path);
        }
    }
} 

Then I'd modify the original code so that it uses the new namespace:

using IO.Abstractions;

public void SomeMethod()
{
    ...
    if(File.Exists(myFile))
    {
        ...
    }
    ...
}

Then, in your test, you can just provide an alternative implementation of the behaviour for File.Exists, something like:

[Test]
public void SomeTest()
{
    // arrange
    ...
    File.ExistsImpl = (path) => true; // to just default to true for every call
    ...

    // act
    someClass.SomeMethod();

    // then assert
    ...
}

I wrote a blog with some more details recently here.

Upvotes: 0

Related Questions