我想创建一个单元测试以确保方法使用 xUnit 和 Moq 记录错误。此代码适用于 ASP.NET Core 2.1:
//Arrange
var logger = new Mock<ILogger<MyMiddleware>>();
var httpContext = new DefaultHttpContext();
var middleware = new MyMiddleware(request => Task.FromResult(httpContext), logger.Object);
//Act
await middleware.InvokeAsync(httpContext);
//Assert
logger.Verify(x => x.Log(LogLevel.Error, It.IsAny<EventId>(), It.IsAny<FormattedLogValues>(), It.IsAny<Exception>(), It.IsAny<Func<object, Exception, string>>()), Times.Once);
Run Code Online (Sandbox Code Playgroud)
为了验证_logger.LogError("Error message");在middleware.InvokeAsync.
但是,在 ASP.NET Core 3.0 中,我无法验证是否正在调用记录器。Microsoft.Extensions.Logging.Internal不能再引用,所以FormattedLogValues不可用。
我尝试更改Assert()to useobject而不是FormattedLogValues,而且IReadOnlyList<KeyValuePair<string, object>>因为那FormattedLogValues是基于(FormattedLogValues.cs)。
这是我在 Visual Studio 测试运行程序中收到的错误消息:
Message:
Moq.MockException :
Expected invocation …Run Code Online (Sandbox Code Playgroud)