google / googletest

GoogleTest - Google Testing and Mocking Framework
https://google.github.io/googletest/
BSD 3-Clause "New" or "Revised" License
34.45k stars 10.07k forks source link

Add WaitForAndClearExpectations() for testing async side effects #1967

Closed calder closed 5 years ago

calder commented 5 years ago

Would it be reasonable to add the following helper to gmock-spec-builders for testing functions with asynchronous side effects?

bool Mock::WaitForAndClearExpectations(void* mock_obj, std::chrono::nanoseconds timeout);
gennadiycivil commented 5 years ago

@calder Thank you for this proposal. Could you please provide more details, potential use case, and most importantly how are you accomplishing this "today"? Thanks again

calder commented 5 years ago

@gennadiycivil: Thanks! Here's an example use case:

Let's say we want to test the behavior of Foo::DoSomething().

If Bar::DoSomethingElse() were called synchronously, we would just create a mock Bar, pass it to Foo's constructor, set up expectations on the Bar mock, and call Foo::DoSomething().

Instead, because it's asynchronous, after calling Foo::DoSomething() we have to either:

So far I have usually opted for "sleep synchronization" with all its associated problems.

calder commented 5 years ago

@gennadiycivil: Does https://github.com/abseil/googletest/pull/1991 look like roughly the right direction?

leunMar commented 5 years ago

@calder @gennadiycivil This would be a very useful feature for testing in ROS, where we have asynchronous callbacks (http://wiki.ros.org/roscpp/Overview/Publishers%20and%20Subscribers).

Actually, there is another workaround: You can wake up a sleeping thread when the mock function is called defining an appropriate action. https://github.com/PilzDE/pilz_robots/blob/5a969f06e6b7626e2ddb3c485f0a5ca645bbaff4/prbt_hardware_support/test/include/prbt_hardware_support/async_test.h

gennadiycivil commented 5 years ago

See #1991