小编brl*_*brl的帖子

如何检查 ASP.NET Core 3.0 的单元测试中是否记录了错误?

我想创建一个单元测试以确保方法使用 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)

c# moq xunit.net asp.net-core asp.net-core-3.0

3
推荐指数
1
解决办法
1446
查看次数

标签 统计

asp.net-core ×1

asp.net-core-3.0 ×1

c# ×1

moq ×1

xunit.net ×1