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?
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.
Data Flow Testing Control Flow Testing Branch Coverage Testing Statement Coverage Testing Decision Coverage Testing.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With