我想用Foq来模拟IBus。
IBus
上的一个方法是OpenPublishChannel
,它返回一个IPublishChannel。IPublishChannel反过来有一个Bus
属性,返回父IBus
。
我当前的代码如下,但显然它不能编译,因为mockBus没有被我需要的点定义。有没有一种方法可以像这样设置递归模拟而不创建两个接口的模拟?
open System
open EasyNetQ
open Foq
let mockChannel =
Mock<IPublishChannel>()
.Setup(fun x -> <@ x.Bus @>).Returns(mockBus)
.Create()
let mockBus =
Mock<IBus>()
.Setup(fun x -> <@ x.OpenPublishChannel() @>).Returns(mockChannel)
.Create()
Foq支持Returns: unit -> 'TValue方法,因此您可以惰性地创建一个值。
使用一点突变实例可以相互引用:
type IPublishChannel =
abstract Bus : IBus
and IBus =
abstract OpenPublishChannel : unit -> IPublishChannel
let mutable mockBus : IBus option = None
let mutable mockChannel : IPublishChannel option = None
mockChannel <-
Mock<IPublishChannel>()
.Setup(fun x -> <@ x.Bus @>).Returns(fun () -> mockBus.Value)
.Create()
|> Some
mockBus <-
Mock<IBus>()
.Setup(fun x -> <@ x.OpenPublishChannel() @>).Returns(fun () -> mockChannel.Value)
.Create()
|> Some