Code coverage for async methods

后端 未结 4 1195
刺人心
刺人心 2021-01-17 17:50

When I analyse code coverage in Visual Studio 2012, any of the await lines in async methods are showing as not covered even though they are obviously executing since my test

4条回答
  •  太阳男子
    2021-01-17 18:27

    There are situations where I don't care about testing the async nature of a method but just want to get rid of the partial code coverage. I use below extension method to avoid this and it works just fine for me.

    Warning "Thread.Sleep" used here!

    public static IReturnsResult ReturnsAsyncDelayed(this ISetup> setup, TResponse value) where TClass : class
    {
        var completionSource = new TaskCompletionSource();
        Task.Run(() => { Thread.Sleep(200); completionSource.SetResult(value); });
        return setup.Returns(completionSource.Task);
    }
    

    and the usage is similar to the Moq's ReturnsAsync Setup.

    _sampleMock.Setup(s => s.SampleMethodAsync()).ReturnsAsyncDelayed(response);
    

提交回复
热议问题