Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write unit test for network client?

I need to write simple http client. It could be great to have unit tests for my class. But I don't know how to write proper and testable class.

For example, I have a client like this:

class HTTPClient
{
public:
     HTTPCLient(const std::string& host, const std::string& port): session(host, port) {}

     void send()
     {
         session.sendRequest(someRequest);
         Response response = session.receiveResponse();
         // ...
     }

private:
    SomeLibrary::ClientSession session;
};

How to test send method (that I really send what I want)? I can't mock it. I can write that HTTPClient receives SomeLibrary::ClientSession object in constructor (in test I would pass mock) but is it good design? I think that the way of implementing of session etc. should by hidden in my class.

Do You have any idea?

like image 981
peter55555 Avatar asked Apr 07 '16 01:04

peter55555


People also ask

How do you write a unit test?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.

What is example unit test?

Data Flow Testing Control Flow Testing Branch Coverage Testing Statement Coverage Testing Decision Coverage Testing.

What are the three steps in a unit test?

The idea is to develop a unit test by following these 3 simple steps: Arrange – setup the testing objects and prepare the prerequisites for your test. Act – perform the actual work of the test. Assert – verify the result.


1 Answers

I happned to have written an HTTP client library the other day.

To test the HTTP client library, I just wrote simple test code that started a std::thread listening on some random port on localhost. Then I told the client to make a test request with the host and the port parameters, as in your case, pointing to the port that my thread was now listening on. The thread's code was programmed to accept a connection, read an HTTP request, save it, and then respond with a canned HTTP response.

And that's how I tested my client library, verifying both the actual request the client sent, and how the client handled the canned HTTP response. Later on, I developed this unit test code to send various kinds of HTTP errors, and malformed HTTP responses, in order to test and verify how the client code handled those situations.

And, for a good measure, the whole thing was guarded by an alarm() call, so if something got stuck in an infinite loop, or so, the entire process will eventually commit suicide.

And that's how you can test your own code too, the same way.

like image 106
Sam Varshavchik Avatar answered Sep 20 '22 21:09

Sam Varshavchik