我很难用Foq来伪装微软的ILogger。
module MockExample
open Microsoft.Extensions.Logging
open NUnit.Framework
open Foq
//open Foq.Linq
// Implementation
type Worker (logger:ILogger) =
member this.DoSomething (ok:bool) =
if ok then
logger.LogInformation("success 1")
else
logger.LogError("error 1")
// Test file
[<Test>]
let ``When error should log error`` () =
// 1. let logger = Mock<ILogger>().SetupAction(fun lg -> lg.LogError("error")) ...Create() not availabe
// 2.
//let loggerMock = Mock<ILogger>();
//loggerMock.SetupFunc(fun lg -> lg.LogError(It.IsAny<string>())) |> ignore // .Returns() is not usable
//let logger = loggerMock.Create()
let logger = mock()
// act
Worker(logger).DoSomething(false)
verify <@ logger.LogError("error 1") @> once
//verify <@ logger.LogError("success 1") @> never考试不及格。
我还尝试了其他语法,试图“模仿”LogError签名,但不使用cuccess。
编辑
我正试图嘲弄真正的记录器方法.Log(logLevel, message, ...),但仍然无法让它正常工作:

实际上,我不知道该如何嘲笑这一点:
member Log<'TState> : logLevel: LogLevel * eventId: EventId * state: 'TState * ``exception`` : exn * formatter: System.Func<'TState,exn,string> -> unit要提取/注册/比较state (它包含日志“消息”)。
编辑2
作为一种解决办法,我写了我对ILogger的嘲弄,它达到了目的,但我的问题仍然是“如何使用Foq来实现它”?
type LoggerMock () =
let mutable informations:string list = []
let mutable errors:string list = []
member this.LoggedInformations = informations
member this.LoggedErrors = errors
interface ILogger with
member this.Log(logLevel: LogLevel, eventId: EventId, state: 'TState, ``exception``: exn, formatter: System.Func<'TState,exn,string>): unit =
match logLevel with
| LogLevel.Information -> informations <- informations @ [state.ToString()]
| LogLevel.Error -> errors <- errors @ [state.ToString()]
| _ -> ()
member this.BeginScope(state: 'TState): System.IDisposable =
raise (NotImplementedException())
member this.IsEnabled(logLevel: LogLevel): bool =
raise (NotImplementedException())
[<Test>]
let ``When error should log error (custom mock)`` () =
let logger = LoggerMock()
Worker(logger).DoSomething(false)
logger.LoggedErrors |> should contain "error 2"发布于 2022-05-31 14:09:58
问题是,.LogError和.LogInformation实际上不是ILogger上的方法,而是包装ILogger实际定义的日志方法的扩展方法。
您需要模拟的方法是:ILogger.Log法
我相信扩展方法都称之为这一种方法。
https://stackoverflow.com/questions/72445519
复制相似问题