Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 527
dr. evil Avatar asked Apr 12 '09 16:04

dr. evil


People also ask

Is unit testing really necessary?

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.

What should not be unit tested?

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.

When should you do unit testing?

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.


2 Answers

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.

like image 53
Jon Skeet Avatar answered Oct 06 '22 23:10

Jon Skeet


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.

like image 31
Darren Clark Avatar answered Oct 06 '22 22:10

Darren Clark