micahhoover
micahhoover

Reputation: 2160

C#: DI with static class for unit tests

I have some legacy code that accesses our database. I'd like to create an interface for each one of these classes for IoC/DI in unit testing.

All of the methods in these classes are static.

When I try to "extract an interface" via VisualStudio, it fails and says, "Could not extract an interface: The type does not contain any member that can be extracted to an interface".

There are some links that explain why interfaces shouldn't have static methods here and here.

This restriction appears to be mostly in support of polymorphism ... which I don't really care about right now and these classes don't really inherit from anything (other than Object).

So how do I use IoC to get an object I can pull data from?

I'd rather not make instance methods since instances increase the working set.

Upvotes: 1

Views: 647

Answers (2)

NikolaiDante
NikolaiDante

Reputation: 18649

Depending on the goal, you could use something like Microsoft Fakes, in particular shims to intercept the static calls to bring the legacy code under a test harness.

Once your library is covered with tests you can have these as a safety net while you introduce proper DI, removing the statics if desired and fully isolated tests.

The danger is that shims are evil and can let developers get away with bad practice.

Upvotes: 1

NikolaiDante
NikolaiDante

Reputation: 18649

One technique could be to abstract the static classes away with a wrapper.

public MyStaticWrapper : IMyStaticWrapper
{
   public void SomeMethod(string something)
   {
      MyStatic.SomeMethod(something); 
   }
}

Then you can inject the IStaticWrapper where needed.


Sorry - just seen this bit....

I'd rather not make instance methods since instances increase the working set.

Tho I'm not sure if it would meet this requirement, but the footprint of the change is relatively small IMO. Personally I would agree with @DStanleys comment.

Upvotes: 3

Related Questions