将 Foq 与 F# 函数类型结合使用

Rya*_*yan 5 .net f# unit-testing mocking foq

例如,我使用 F# 类型定义来防止函数之间的硬依赖

type IType1 = int -> int
type IType2 = int-> string

let func1 (i : int) : int = i * i
let func2 (i : int) : string = i |> string

let higherFunc (dep1 : IType1) (dep2 : IType2) (input : int) : string =
    input |> dep1 |> dep2

let curriedFunc = higherFunc func1 func2
let x = curriedFunc 2
Run Code Online (Sandbox Code Playgroud)

输出x:“4”

显然,这是非常人为且简单的,但想象一下依赖项是一个解析器和一个排序器或其他什么。我正在编写的更小的功能颗粒。

我正在尝试使用 Foq 来帮助我的单元测试装置。这是我正确使用 F# 的第一周,我很难尝试弄清楚如何配置这些类型的模拟。

有两件事值得一提:

1 - 如果我使用抽象类,我可以让它工作,但我不想这样做,因为对于完全相同的最终结果来说,这会带来更多麻烦。例如

type IType1 = 
    abstract member doSomething : int -> int

type func1 () =
    interface IType1 with
        member this.doSomething (i: int) = i * i
Run Code Online (Sandbox Code Playgroud)

允许我设置一个模拟

let mT1= Mock.With (fun (x : IType1) -> <@ x.doSomething(any()) --> 5 @>)
Run Code Online (Sandbox Code Playgroud)

但我真的不想这样做。

2 - 如果我只是使用

type IType1 = int -> int
let mT1 = Mock.Of<IType1>()
Run Code Online (Sandbox Code Playgroud)

然后我返回一个有效值,但是如果我尝试以任何方式配置它,例如

let mT1= Mock<IType1>.With (fun x -> <@ x(any()) --> 5 @>)
Run Code Online (Sandbox Code Playgroud)

或者

let mT1= Mock<IType1>.With (fun x -> <@ any() --> 5@>)
Run Code Online (Sandbox Code Playgroud)

然后我得到一个例外

System.NotSupportedException : Expected standard function application: Call 
Run Code Online (Sandbox Code Playgroud)

或者

System.NotSupportedException : Expected standard function application: ValueWithName 
Run Code Online (Sandbox Code Playgroud)

我希望我只是对语法感到愚蠢,并且可以做我想做的事。我已经尝试了我能想到的所有变体,包括 .Setup(conditions).Create() 的变体,但我在源代码中找不到任何示例。

我显然可以轻松地制作自己的模拟,例如

let mT1 (i : int) : int = 5
Run Code Online (Sandbox Code Playgroud)

因为任何适合 int -> int 签名的东西都是有效的,但是如果我想检查该函数是否为 i 传递了某个值,我必须放入日志记录步骤等。如果有Foq 负责一些繁重的工作。

编辑 我刚刚注意到根模拟对象在其签名中具有“需要引用类型”(即 Mock<'TAbstract(需要引用类型)> ) - 这是否意味着我没有机会模拟值?如果我不配置模拟,它怎么管理它?

Fyo*_*kin 4

你不必嘲笑。如果您的依赖项只是函数类型,则可以只提供函数:

let mT1= fun x -> 5
Run Code Online (Sandbox Code Playgroud)

对象模拟的整个概念是(必须)由面向对象的人们发明的,以弥补对象不能很好地组合(或根本不能组合)的事实。当您的整个系统正常运行时,您可以当场创建功能。没有必要嘲笑。

如果你真的沉迷于使用 Foq 的设施,如日志记录和验证(我敦促你重新考虑:你的测试会变得更容易、更有弹性),你总是可以让自己成为一个对象,充当你的代理主机。功能:

type ISurrogate<'t, 'r> =
    abstract member f: 't -> 'r

// Setup
let mT1 = Mock.Create<ISurrogate<int, int>>()
mT1.Setup(...)...

let mT2 = Mock.Create<ISurrogate<int, string>>()
mT2.Setup...

higherFunc mT1.f mT2.f 42

mT1.Received(1).Call( ... ) // Verification
Run Code Online (Sandbox Code Playgroud)

这样,丑陋的地方就仅限于您的测试,并且不会使您的生产代码变得复杂。

显然,这仅适用于单参数函数。对于具有多个柯里化参数的函数,您必须对参数进行元组并在注入站点将调用包装在 lambda 中:

// Setup
let mT1 = Mock.Create<ISurrogate<int * int, int>>()

higherFunc (fun x y -> mT1.f(x, y)) ...
Run Code Online (Sandbox Code Playgroud)

如果您发现这种情况经常发生,您可以打包 lambda 创建以供重用:

let inject (s: ISurrogate<_,_>) x y = s.f (x,y)

higherFunc (inject mT1) ...
Run Code Online (Sandbox Code Playgroud)