如何在netcore 3.0上模拟ILogger.LogXXX方法

Lui*_*reu 5 moq .net-core-3.0 ilogger

到目前为止,我们都是ILogger.LogXXX通过这种方式来模拟调用的。

不幸的是,在将项目更新到.net core 3.0之后,如果您使用严格的模拟(Moq),它总是会抱怨没有相应的设置:

Moq.MockException : ILogger.Log<FormattedLogValues>(LogLevel.Information, 0, 
           Inicio de cancelamento de reserva:  Grm.GestaoFrotas.Dtos.Reservas.Mensagens.MsgCancelamentoReserva, 
           null, 
           Func<FormattedLogValues, Exception, string>) invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不能FormattedLogValues像这样简单地更改对象:

_container.GetMock<ILogger<GestorReservas>>()
          .Setup(l => l.Log(It.IsAny<LogLevel>(),
                            It.IsAny<EventId>(),
                            It.IsAny<FormattedLogValues>(),
                            It.IsAny<Exception>(),
                            It.IsAny<Func<FormattedLogValues, Exception, string>()));
Run Code Online (Sandbox Code Playgroud)

这不会起作用,因为它FormattedLogValues是内部的。

我总是可以更改模拟策略(从严格到宽松),但我更愿意保持原样(严格)。那么,有关于如何解决这个问题的线索吗?

谢谢。

小智 4

尝试这个:

//    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
//    <PackageReference Include="Moq" Version="4.13.1" />

container.GetMock<ILogger<GestorReservas>>()
          .Setup(l => l.Log(It.IsAny<LogLevel>(),
                            It.IsAny<EventId>(),
                            It.IsAny<It.IsAnyType>(),
                            It.IsAny<Exception>(),
                            (Func<It.IsAnyType, Exception, string>)It.IsAny<object>())));
Run Code Online (Sandbox Code Playgroud)

https://www.bountysource.com/issues/79804378-cannot-verify-calls-to-ilogger-in-net-core-3-0-preview-8-generic-type-matcher-doesn-t-work-与验证