cHorse1981
cHorse1981

Reputation: 121

How to test asynchronous callback with gtest

I am attempting to write a unit test for a function that takes a callback as a parameter. The function will make an asynchronous network call and call the callback when done. In the below code the EXPECT_TRUE in the callback isn't being evaluated because it is happening after the test has completed (or something like that). How do I write the test so the results of the asynchronous callback are evaluated properly?

MyManager *manager = [[MyManager alloc] init];
EXPECT_FALSE(IsNil(manager));
        
[manager setupWithData:data completion:^(MyResponse *response) {
      EXPECT_TRUE(response.errorCode == RequestSuccess);
}];

Upvotes: 1

Views: 947

Answers (1)

Quarra
Quarra

Reputation: 2695

If you can inject your callback to the code under test, you can set an std::atomic_bool flag inside your callback and check its status at the end of your test for some limited time (the time depends on how long it may take to perform the async operation):

std::atomic_bool callback_called_flag{false};
auto callback = [this]() { callback_called_flag = true; }};

// inject the callback to you code here

// start the async operation here

// wait for e.g. 1000 ms
int retry_count = 100;
while (!callback_called_flag && retry_count-- > 0)
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
ASSERT_TRUE(callback_called_flag);

Upvotes: 1

Related Questions