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
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.
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.