Unit Testing – Is It Worth Unit-Testing an API Client?

apiunit testing

This is something that's been troubling me for a while now. Is it actually worth unit-testing an API client?

Let's say you're creating a small class to abstract-away the calls to a petshop REST API. The petshop is a very simple API, and it has a basic set of methods:

  • listProducts()
  • getProductDetails(ProductID)
  • addProduct(...)
  • removeProduct(ProductID)

In testing this, we'd have to either create a mock service or mock the responses. But that seems overkill; I understand that we want to make sure that our methods don't stop working through typo/syntax errors, but since we're writing functions that call remote methods and then we're creating fake responses from those remote methods, it does seem like a waste of effort and that we're testing something that can't really fail. Worse, if the remote method changes our unit tests will pass while production use fails.

I'm pretty sure I'm missing something, or I've got the wrong end of the stick, or I'm not seeing the wood for the trees. Can someone set me on the right track?

Best Answer

The job of a remote API client is to issue certain calls - no more, no less. Therefore, its test should verify that it issues those calls - no more, no less.

Sure, if the API provider changes the semantics of their responses, then your system will fail in production. But that isn't your client class's fault; it's something that can only be caught in integration tests. By relying on code not under your control you have given up the ability to verify correctness via internal testing - it was a trade-off, and this is the price.

That said, testing a class that consists only of delegations to another class may be low-priority, because there is comparatively little risk of complex errors. But that goes for any class that consists only of uniform one-liners, it has nothing to do with calling out into another vendor's code.

Related Topic