Unit tests and several asynchronous tasks

I am creating unit tests to help create code that will receive and download (if necessary) incoming requests from my controller.

In my unit test, I want two lines of code to fire at the same time, albeit with a 2 second delay between calls. This allows me to start the first branch of my logic, and then in the second call, because the data already passed is used by an alternative branch of logic.

I came close, but he feels dirty. I use the following, which immediately disconnects my first call and moves on to the next lines of code.

Task.Factory.StartNew(() => stubbedQueueHandler.QueueProcessor(setupModel));

Thread.Sleep(2000);
//second call
stubbedQueueHandler.QueueProcessor(setupModel);

await Task.Delay(10000);

However, the unit test terminates before the first call termination, which in turn kills the process. The only way to complete the first call is to put a line await Task.Delay()that does the trick.

I understand why he does this because I effectively transferred the call without waiting for a response. I don’t want to start using task delays, and I’m sure that it’s just my understanding that the problem is in asynchronous programming: o).

+4
source share
2 answers

You need to capture Task, which starts QueueProcessorand waits for it after calling the stub a second time:

public async Task FooTestAsync()
{
    var task = Task.Run(() => stubbedQueueHandler.QueueProcessor(setupModel));
    await Task.Delay(2000);

    stubbedQueueHandler.QueueProcessor(setupModel);
    await task;
}

, , QueueProcessor .

+4

Thread.Sleep() .

5 "Async Way" Doing Things:

To Do This                                Instead of This            Use This
Retrieve the result of a background task  Task.Wait or Task.Result   await
Wait for any task to complete             Task.WaitAny               await Task.WhenAny
Retrieve the results of multiple tasks    Task.WaitAll               await Task.WhenAll
Wait a period of time                     Thread.Sleep               await Task.Delay

. , .

+3

Source: https://habr.com/ru/post/1615278/


All Articles