How do you unit-test a TCP Server? Is it even worth it?

后端 未结 8 1232
一整个雨季
一整个雨季 2021-02-05 10:03

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

相关标签:
8条回答
  • 2021-02-05 10:54

    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.

    0 讨论(0)
  • 2021-02-05 10:59

    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.

    0 讨论(0)
提交回复
热议问题