What is the correct way to test this problem?

I have a method that repeats work using a task and asynchronously / waits.

    public static Task ToRepeatingWork(this Action work, int delayInMilliseconds)
    {
        Action action = async () =>
        {                
            while (true)
            {
                try
                {
                    work();
                }
                catch (MyException ex)
                {
                    // Do Nothing
                }
                await TaskEx.Delay(new TimeSpan(0, 0, 0, 0, delayInMilliseconds));
            }
        };
        return new Task(action, SomeCt, TaskCreationOptions.LongRunning);
    }

I wrote the corresponding test:

    [TestMethod, TestCategory("Unit")]
    public async Task Should_do_repeating_work_and_rethrow_exceptions()
    {
        Action work = () =>
        {
            throw new Exception("Some other exception.");
        };

        var task = work.ToRepeatingWork(1);
        task.Start();
        await task;
    }

I expect this test to fail, but it will pass (and the test runner will fail).

However, if in the ToRepeatingWork method I change the action from async to the normal action and use Wait instead of waiting, the test behaves as expected.

TaskEx.Delay(new TimeSpan(0, 0, 0, 0, delayInMilliseconds)).Wait();

What is wrong here?

+4
source share
1 answer

You should never use the task constructor. If you have work to put in a thread pool, use Task.Run. This is a problem, but not something that causes a crash.

async void, Func<Task> Action. , .

public static Task ToRepeatingWork(this Action work, int delayInMilliseconds)
{
  Func<Task> action = async () =>
  {                
    while (true)
    {
      try
      {
        work();
      }
      catch (MyException ex)
      {
        // Do Nothing
      }
      await TaskEx.Delay(new TimeSpan(0, 0, 0, 0, delayInMilliseconds));
    }
  };
  return Task.Run(() => action());
}

[TestMethod, TestCategory("Unit")]
public async Task Should_do_repeating_work_and_rethrow_exceptions()
{
  Action work = () =>
  {
    throw new Exception("Some other exception.");
  };

  var task = work.ToRepeatingWork(1);
  await task;
}
+1

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


All Articles