Skip to content

Instantly share code, notes, and snippets.

@toddbranch
Created January 25, 2017 14:32
Show Gist options
  • Save toddbranch/01ca15b9312fa6cb4433a7e907fad692 to your computer and use it in GitHub Desktop.
Save toddbranch/01ca15b9312fa6cb4433a7e907fad692 to your computer and use it in GitHub Desktop.
Testing Threads
void MyClass::FetchMagicNumber(std::function<void(int)> callback) {
std::weak_ptr<MyClass> weak_this = shared_from_this();
auto fetch_results = [weak_this] {
auto shared_this = weak_this.lock();
if (!shared_this) return -1;
return shared_this->requester_->DoLongWebRequest();
};
system::Runtime::net_io.Post<int>(fetch_results, callback, system::Runtime::ui());
}
void MyClass::FetchMagicNumber(std::function<void(int)> callback,
const system::JobRunner* request_thread,
const system::JobRunner* callback_thread) {
std::weak_ptr<MyClass> weak_this = shared_from_this();
auto fetch_results = [weak_this] {
auto shared_this = weak_this.lock();
if (!shared_this) return -1;
return shared_this->requester_->DoLongWebRequest();
};
request_thread.Post<Stuff>(fetch_results, callback, callback_thread);
}
TEST(MyClassTest, CallsCallbackWithResult) {
constexpr int kAnswerToLifeTheUniverseAndEverything = 42;
constexpr int kErrorCode = -1;
MockRequester requester;
ON_CALL(requester, DoLongWebRequest()).WillByDefaultReturn(kAnswerToLifeTheUniverseAndEverything);
std::shared_ptr<MyClass> instance = MyClass::Create(&requester);
MockFunction<void(std::unique_ptr<Stuff>)> callback;
EXPECT_CALL(callback, Call(kAnswerToLifeTheUniverseAndEverything));
system::NonBlockingJobRunner request_thread;
system::NonBlockingJobRunner callback_thread;
instance.FetchStuff(callback, &request_thread, &callback_thread);
request_thread.ExecuteAll();
callback_thread.ExecuteAll();
}
TEST(MyClassTest, CallsCallbackWithErrorCode) {
constexpr int kAnswerToLifeTheUniverseAndEverything = 42;
constexpr int kErrorCode = -1;
MockRequester requester;
ON_CALL(requester, DoLongWebRequest()).WillByDefaultReturn(kAnswerToLifeTheUniverseAndEverything);
std::shared_ptr<MyClass> instance = MyClass::Create(&requester);
MockFunction<void(std::unique_ptr<Stuff>)> callback;
EXPECT_CALL(callback, Call(kErrorCode));
system::NonBlockingJobRunner request_thread;
system::NonBlockingJobRunner callback_thread;
instance.FetchStuff(callback, &request_thread, &callback_thread);
instance.reset();
request_thread.ExecuteAll();
callback_thread.ExecuteAll();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment