Strategy to create a third-party library interface?

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

I would make fun of the class to avoid its dependencies on the file system, since my code really only worried about the results of this code.

What is the best strategy used to mock specific library classes without modifying the original library?

I think I can create a wrapper object that implements the interface and contains the original library object. However, I want to make sure that there is no better way before I start this way.

Or, can a tool like TypeMock be better than Moq?

+6
source share
1 answer

Background:

If this is not a stable library / framework like the .NET framework, I prefer to separate my code from it. That is, I like the library to depend on my system, and not vice versa.

Modify, rephrase: you can consider the library in which you use "stable". However, since it interacts with an "external" system (file system), I probably still want to separate my system from it.

To do this, I create an adapter / wrapper for the library. The interface has methods that my system wants to have in the library, and not those that the library provides. The interface uses types that my system owns, not a library. The adapter makes the necessary conversions.

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

Answer your question:

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

Whether you use a mock framework or write your fakes for an adapter is a matter of taste.

+10
source

Source: https://habr.com/ru/post/954929/


All Articles