Automated way to write a wrapper and interface for dependency injection of third party libraries?

时间:2015-07-28 15:47:53

标签: c# unit-testing dependency-injection wrapper

I'm using a third party library class Foo that has several public methods and properties that my class uses as a dependency.

I want to test my class and mock the Foo object, but it does not have an interface. So I was thinking, I could inherit the class in a class of my own, extract an interface, and voila! I would have an injectable interface.

...but of course there are complications. Foo has a bunch of public fields. These can't go into an interface, so I'd have to write property wrappers for the fields. It's annoying.

Is there an automated way to do this? I have ReSharper, but there doesn't seem to be a way to automagically do this, which means I'm writing a lot of tedious code.

2 个答案:

答案 0 :(得分:3)

You should split your class under test into two separate classes. One class that contains the (business) logic that you need to test, and a second class that acts as an adapter to the external dependency. This adapter class should implement an interface and the logic class should depend on that interface. This interface should not mimic the API of the external dependency, but the interface should be defined in the application's needs. By doing this you achieve that you:

  • adhere to the Single Responsibility Principle, because currently your class under tests has two responsibilities.
  • adhere to the Dependency Inversion Principle by placing the new adapter behind an abstraction. This prevents your application from having to take a dependency on the external tool (only your composition root needs to depend on it), which makes your application more testable, and more maintainable.
  • adhere to the Interface Segregation Principle, that states that interfaces should be narrow and defined for the role they participate in.

What you'll end up with is an adapter class that is tightly coupled to the external library. This adapter will transform an incoming call to something that it can send on to the external library. This adapter can't be tested in isolation, and if testing is important, you'll probably need integration tests for this (depending on how the external library functions). Important to say is that you don't have to test that the external library works, but you probably still want to test the correctness of the adapter class.

答案 1 :(得分:2)

I would create a wrapper class that uses and interface you have designed that only expose what you need from Foo.

So for example:

class MyFooWrapper : IFoo
{
   private Foo _foo;
    // methods exposed by IFoo
 }

You could take further by making MyFooWrapper an abstract class to contain the properties and any other base functionality but don't put Foo in there , instead have a class that inherits the foo wrapper .