kdmurray
kdmurray

Reputation: 3048

What is the most "testable" way to use static reference information in an application?

I have an application which needs to reference a set of reference codes (a 3-char code and it's associated short description). The data doesn't change -- or at least I've never known it to change in the past -- but I still have a problem hard-coding it into the application code.

My original thought was to create a static class to reference within the application and load this information from some sort of configuration file at runtime. My problem is that I don't know how to make it testable.

My newbie unit-testing questions are:

How do I get the data into the static reference class without creating a dependency on the config file?

How do I make this static reference class testable?

Upvotes: 2

Views: 113

Answers (1)

Sergey Teplyakov
Sergey Teplyakov

Reputation: 11657

You can create interface for your configuration class, and than depend upon this interface instead of some concrete implementation (this is called Dependency Inversion Principle):

interface ISomeData
{
  IEnumerable<string> YourData {get;}
}

class SomeData
{
  // This class is a singleton that could read
  // all apropriate data from application configuration file into SomeData
  // instance and then return this instance in following property
  public static ISomeData {get;}
}

class YourClass
{
  private readonly ISomeData _someData;

  public YourClass(ISomeData someData)
  {
    _someData = someData;
  }

  // You can even create additional parameterless constructor that will use
  // your singleton
  pbulic YourClass()
    : this(SomeData.Instance)
  {}
}

And then you can create an unit test easily because you can "mock" you ISomeData interface with fake implementation and pass instance of this mock object into YourClass constructor.

// Somewhere in unit test project

class SomeDataMock : ISomeData
{
  // you should implement this method manually or use some mocking framework
  public IEnumerable<string> YourData { get; }
}

[TestCase]
public void SomeTest()
{
  ISomeData mock = new SomeDataMock();
  var yourClass = new YourClass(mock);
  // test your class without any dependency on concrete implementation
}

As I mentioned before you can use some mocking framework or use something like Unity that could help implement all of this.

Upvotes: 1

Related Questions