In order to create a very testable codebase, I abstracted away a certain external dependency. To be precise, this dependency is actually implemented by a vendor SDK and it communicates directly with a hardware. As such, this is the interface:
public interface IHardware
{
void Send(IMessage message);
event EventHandler<MessageEventArgs> OnMessage;
}
(The communication with the hardware is fully assyncronous)
As soon as this is initialized, events may be raised by the hardware (through the the OnMessage event). Client code can send messages any time, and possible responses will be received in the form of events.
Now, this very simple interface needs to be implemented; The implementation is just a delegation to the actual SDK class. The problem is this: how I write tests to provoke the proper implementation?
9
As you noticed, the TDD mantra of only writing code in response to a failing (unit) test starts to break down when you approach a system boundary where you need to integrate with hardware or third-party code.
You started out right by defining an abstraction layer over the SDK (in the form of the IHardware
interface) and writing your code against that interface.
As it is unlikely that the IHardware
implementation can be subjected to automatic unit tests in a meaningful way, you may have to let the ideal of TDD go for that part of the project. However, not all is lost:
- With a bit of luck, the adaptation layer is simple enough that it can be verified by reviewing the code
- The SDK you are wrapping is likely to be well tested already
- You can still test the combination of SDK and adaptation layer with higher-level tests, such as integration tests and acceptance tests. These tests you will need anyway to prove the entire system works correctly.
1
Abstracting away the 3rd party dependency like you did does not only benefit testing, as it also makes your code more robust against changes in the dependency (by effectively wrapping it/creating your own adapter).
Testing that the real 3rd party product does what you think it does when receiving commands from your code might not be possible in the context of unit testing. However, what you can do is to verify that your Adapter works as you expect it to. Sending commands when you expect it to and acts accordingly when messages are received.
Example:
[TestMethod]
public void shutdown_on_receiving_off_signal() {
HardwareMock mock = new HardwareMock(); //implements IHardware, and replaces the 3PP in your tests.
ThirdPartyAdapter adapter = new ThirdPartyAdapter(mock);
adapter.shutdown(); //send shutdown command to the IHardware impl.
AssertMockReceived(OFF_SIGNAL);
}