Await a Async Void method call for unit testing

前端 未结 8 1503
北荒
北荒 2020-12-04 17:25

I have a method that looks like this:

private async void DoStuff(long idToLookUp)
{
    IOrder order = await orderService.LookUpIdAsync(idToLookUp);   

             


        
相关标签:
8条回答
  • 2020-12-04 18:03

    You can use an AutoResetEvent to halt the test method until the async call completes:

    [TestMethod()]
    public void Async_Test()
    {
        TypeToTest target = new TypeToTest();
        AutoResetEvent AsyncCallComplete = new AutoResetEvent(false);
        SuccessResponse SuccessResult = null;
        Exception FailureResult = null;
    
        target.AsyncMethodToTest(
            (SuccessResponse response) =>
            {
                SuccessResult = response;
                AsyncCallComplete.Set();
            },
            (Exception ex) =>
            {
                FailureResult = ex;
                AsyncCallComplete.Set();
            }
        );
    
        // Wait until either async results signal completion.
        AsyncCallComplete.WaitOne();
        Assert.AreEqual(null, FailureResult);
    }
    
    0 讨论(0)
  • 2020-12-04 18:11

    An async void method is essentially a "fire and forget" method. There is no means of getting back a completion event (without an external event, etc).

    If you need to unit test this, I would recommend making it an async Task method instead. You can then call Wait() on the results, which will notify you when the method completes.

    However, this test method as written would still not work, as you're not actually testing DoStuff directly, but rather testing a DelegateCommand which wraps it. You would need to test this method directly.

    0 讨论(0)
提交回复
热议问题