views:

134

answers:

2

I have a class that is responsible for network communication. I would like to have a unit test for it.

Here is where I'm stuck in order to write a test for it i have to implement a server to communicate with but that in turn will require its own test.

How do you write tests for a class such as this?

+5  A: 

Unless you are writing low level drivers, your class undoubtedly depends on other classes to do the actual communications. In that event, I would use dependency injection to supply those classes or wrappers around them, if they aren't easily mocked. In you tests, you'd supply a mock version of the classes you are depending on (or the wrappers if you can't mock the actual classes). Verify that the correct methods with the proper parameters are invoked by your methods on the mocks that you supply. Make sure you have enough unit tests to satisfy yourself that you've covered the full range of behavior from the real dependencies. This will suffice for your unit tests.

You will also need some integrations tests. Unfortunately, the easiest way to do this is probably to develop a full-up mock server to communicate with. Note that your mock server need only implement the interface -- not the actual code on the other end. Supply some extra methods to allow you to set the server up for your integration tests so that the expected behavior with the mock server occurs.

tvanfosson
+1  A: 

If you're unit-testing a class that's responsible for network communication, then you only test that you're doing the communication correctly. So supply a mock (as in, a dummy) server for it to communicate with. There are many mock libraries that you can use such as EasyMock and jMockit. If you want to test an actual communication with an actual server, then that's integration-testing. Of course, the exact definition of what unit-testing encompasses varies from developer to developer.

aberrant80