TDD Unit Testing – How to Test Network Connectivity API

tddunit testing

I'm currently trying to add TDD on my workflow. I fail to create tests where I can easily test a library that requires remote connections.

More precise, my program uses snmp4j library. Currently I'm working with 1 release behind due to I don't know what's the impact of the new API release on my code. So I read that implementing a battery of tests based on what I use from the library I can have a better overview of the impact if I upgrade to the new version. So I have the following question

  • I need to get an snmp response based on a request. Ideally would be that I have control over the machine and I know what to ask and what to expect … but what if that remote machine is down, has network connectivity problems or doesn't exist? Should I create a SNMP agent listening on localhost and have control over which OID I ask and which responses I give? I rely heavy on the type of responses from the OIDs (being Integer32, Gauge32 etc) not the values I receive.

The response doesn't have to be so concrete, actually I would like to read more about this kind of scenarios where you need to test network connectivity through an API.

Best Answer

In their book Growing Object-Oriented Software, Guided by Tests, Steve Freeman and Nat Pryce tackle this very issue. I do recommend that as a worthy read, since it's full of interesting examples and I'll probably just misquote, anyway.

Rephrasing, they argue that instead of mocking the external API you have no control over, you should create a layer of adapter objects. That way you can translate the data to your application's terms and distance the third party code from yours.

I rely heavy on the type of responses from the OIDs (being Integer32, Gauge32 etc) not the values I receive.

Based on what you said, that could be a helpful pattern to adapt to.

However, the authors also state that this pattern may not be applicable if your application relies on value types. So in the end it boils down to: it depends. Abstracting value types may not make sense in this particular case, but if it does, here's an option worth considering.

Related Topic