Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy to make a third-party library implement interfaces?

I would like to write unit tests for some of my classes. Some of my classes depend on a third-party library which uses the file system and has no interfaces to mock.

I'd to mock the class to avoid its dependencies on the filesystem, since my code is really only concerned about the results of that code.

What is the best strategy to use to mock the concrete classes of the library without modifying the initial library?

I'm thinking I might create a wrapper object that implements an interface and contains the initial library's object. However, I want to make sure there's not maybe a better way before I start down this path.

Or, Would a tool like TypeMock be better suited than Moq in this case?

like image 346
SeanKilleen Avatar asked Sep 30 '13 10:09

SeanKilleen


1 Answers

Background:

Unless it's a stable library/framework like the .NET framework, I prefer to decouple my code from it. That is, I like to make the library depend on my system rather than the opposite.

Edit, refrase: You might consider the library you are using "stable". However, since it interacts with an "external" system (the file system), I would probably still want to decouple my system from it.

To accomplish this, I create an adapter/wrapper for the library. The interface has the methods that my system wants the library to have, not the ones that the library happens to provide. The interface uses types that my system owns, not any from the library. The adapter makes any convertions necessary.

This I do whether I want to mock/stub/fake the library or not because it provides a good separation of concerns and also it protects my system against changes in the library.

Answer to your question:

Once the adapter/wrapper is there it's easy to fake it in your tests. As a bonus, since the adapter uses your system's language, it will be easier to write tests that are easy to read and understand.

Whether you use a mock framework or write your own fakes for the adapeter is a matter of taste.

like image 97
Torbjörn Kalin Avatar answered Sep 19 '22 08:09

Torbjörn Kalin