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.
Wrapping third-party libraries is definitely a good practice to follow. It may cost you some extra time, but in the long run you are left with a system which is easier and faster to change.
Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.
Dependency injection helps to develop testable code, allowing developers to write unit tests easily. You can use mock databases with dependency injection, and test your application without affecting the actual database.
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:
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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With