FuncRes Test::test(HttpRequest& request, std::string& result) {
try {
auto httpClientSync = HttpClientSync::create(param);
HttpResponse response = httpClientSync->execute(request);
if (...) {
return FuncRes::SUCCESS;
} else if (...) {
return FuncRes::RETRY;
} else {
return FuncRes::FAILED;
}
} catch (...) {
return FuncRes::RETRY;
} catch (...) {
return FuncRes::FAILED;
}
}
httpClientSync is a local variable, it will destroy when the test is done. I'm confused if I can mock HttpClientSync and "execute" method?
Refactor this function into 2 parts, one that creates real HttpClientSync, and one that accepts HttpClientSync interface:
FuncRes Test::test(HttpClientSync& httpClientSync, HttpRequest& request, std::string& result);
FuncRes Test::test(HttpRequest& request, std::string& result) {
auto httpClientSync = HttpClientSync::create(param);
test(httpClientSync, request, result);
}
Then test variant which accepts HttpClientSync in arguments, and pass mock instead of real client.
If you need to test some other code which calls this test
function, and you still want to mock HttpClientSync, then instead of storing param
in your Test class, store HttpClientSync& client
instance, and pass it in constructor.