Search code examples
unit-testingtestingtddfunctional-testingfunctional-dependencies

tdd - creating tests for 3rd party code


How do I create unit tests if the method or procedure I'm testing against relies on a piece of code from a 3rd party? Say, I have a method that uses classes from a third party source that requires setup that can only be done in a functional test. How should I approach this? Most of the time, the third party dependency can't be mocked, but my method really needs to make use of it.

Also, should I avoid my unit tests or even my functional tests from harnessing actual data? Like, should my tests never connect to a Database API to temporarily add data, operate and test against it, then delete it afterwards?


Solution

  • unit tests

    you should tests everything. but not everything using unit-tests. unit tests don't depend on environment - database, internet connection etc. best practices for working with untrusted/unstable 3rd party tools is to create anti-corruption layer between your code and 3rd party code. so refactor your code to make your business logic as independent as possible. and unit-test the business logic.

    if you're not sure how the 3rd party code works or if it change in the future, you can do 'learning tests'. these are unit-tests (if possible) that assert the behaviour you rely on. in learning tests you test only 3rd party code, not yours

    if the 3rd party code is more-less trusted (well known open-source libraries) then you assume it works, don't do any separation and you unit-test only your code, not the libraries.

    non-unit tests

    if your tests require external environment (db, network etc) then you should do integration tests. its purpose is not to test business logic but rather that if you connected all the parts correctly. sql testing is one the most famous exceptions.

    there is no simple rule how to do integration tests (you can write books about sql testing). it depends what exactly you want to test, how much similarity to your production environment you need/want. for example you may do sql testing against in-memory db or against your production-like db (oracle, postgres etc). however you design your integration tests you must assure that each test starts with know environment state. and you have take into consider errors that leaves environment in dirty state and speed of such tests