I'm developing a small TCP server, which will process some TCP packets and behave differently based on the request.
How can I write unit test for this? If it's really hard to write, is it even worth the effort?
One of the benefits of unit tests is that they isolate a function, class or method and only test that piece of code. Higher quality individual components create overall system resiliency. Thus, the result is reliable code. Unit tests also change the nature of the debugging process.
Do not test anything that does not involve logic. For example: If there is a method in the service layer which simply invokes another method in the data access layer, don't test it.
Unit testing is the first testing phase and it is practiced before moving to the phase of integration testing. Hence, before moving for the next testing level, make sure to fix all the identified bugs in the unit testing phase.
I'd try to extract the TCP-specific bit from the processing bit. Is your protocol really packet-based, or is it stream-based? If it's stream-based you can just make the processing part accept a stream (or possibly a pair of streams, one for input and one for output) and feed it with either a MemoryStream
or your own similar stream implementation giving a bit more control.
Either way, you basically want to mock out the network side of things so you can test the real logic without getting the network involved at all. Testing the network layer (i.e. the thin piece of logic between the framework network classes and the processing logic) may well be a bit harder, but if you can make it thin enough there shouldn't be an awful lot to test.
The first thing to do is to separate the behavior(s) from the TCP packets that are incoming. Abstract that into a dispatch table or other such thing.
Then write unit tests for each of the behaviors independent of how they were invoked. You can test the final TCP -> behavior layer with a test tool you write or borrow. That layer should be almost trivial if the code is factored properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With