MustHaveHappened 断言对于单独线程上的异步方法 运行 总是失败 (Task.Run)

MustHaveHappened Assert always fails for an async method run on a separate thread (Task.Run)

我有一个方法:

public class MyClass
{
    public ILogger _logger;

    public async void TestLogMethod(string msg)
    {
        await Task.Run(async ()=> await _logger.Log(msg));
    }
}

还有一个测试用例:

[Test]
public async Task TestLogMethod_LogMessage_Test()
{
    var fakeLogger = A.Fake<ILogger>();
    var testClass = new MyClass();
    testClass._logger = fakeLogger;

    testClass.TestLogMethod("Test Message");

    A.CallTo(() => fakeLogger.Log(A<string>._)).MustHaveHappened();
}

MustHaveHappened 断言总是失败

Assertion failed for the following call:
MyClass.TestLogMethod<System.Object>(<Ignored>)
Expected to find it at least once but no calls were made to the fake object.

明明调用了_logger.Log(),但是为什么这里Asserting总是失败?

您不是在等待 TestLogMethod 的完成,而是在它发生之前验证预期。 Task 将在线程池上调度,然后该方法将立即 return。这就是为什么你应该 avoid async void 方法。

将方法更改为 return a Task 这样您就可以 await 了。您还可以在此处删除大部分 asyncawait 对,因为它们是多余的:

public Task TestLogMethod(string msg)
{
    return Task.Run(() => _logger.Log(msg));
}

然后 await 在你的测试中:

await testClass.TestLogMethod("Test Message");

然后当验证发生时,对 ILogger.Log 的调用将会发生。