r/cpp_questions • • 5d ago

OPEN Correct way to test async code?

Lets say I have async code or some sort of timer or scheduler that calls a lambda later on some event, how do i test this in simple way in existing frameworks?

Is using futures or other sync mechanism the only way? or a simpler runloop/eventloop style facilities exist in test frameworks to simplify things?

For now looks like the test itself has to take on more theeading/orchestration/synchronization responsibilities.

For event driven and interactive apps, async execution would be common.

9 Upvotes

6 comments sorted by

4

u/KingAggressive1498 5d ago

you should test it the way you plan to run it in the final project.

the "optimal" way is going to be a very case-by-case answer but generally speaking continuation passing will have better runtime characteristics than futures at the cost of code readability and ease of debugging.

1

u/IndividualSituation8 5d ago

Consider the simple case of a timer class which schedules given lambda after give interval, now for the main test code to assert this, i could only think of setting promise in my test lambda and wait for it on my test code using future.get(), to really assert that my lambda was indeed invoked by the timer class

1

u/BartvanIngenSchenau 4d ago

If you are interested in testing the user of the timer class and not the timer class itself, then I see two tests:

  1. A test to verify that (a mock of) the timer class is invoked to call something after the correct timeout.
  2. A test to verify that the behaviour is correct when the timer class makes the callback. This callback can be done without any thread switching immediately after the arrange part of the test received the call to start the timer with the callback in it.

1

u/kevinossia 5d ago

Yeah, you have the right idea

2

u/Independent_Art_6676 4d ago

I second testing it as it would be used, but sometimes the most efficient way to test something is to flat out call it with some test data by brute force. Sometimes that means throwing a test this button on the UI or wiring the new thing into the main event checking loop or whatnot. These kinds of things force it to exercise the new code if the normal way to access the new feature is complex like load a file, select some of the file's contents, do something with that, send the result somewhere else, ... just bypass all that and feed it something you know what is and know what the expected behavior/output should be for those kinds of scenarios.