你能在foq中设置递归模拟吗?

时间:2013-04-23 10:30:50

标签: f# mocking easynetq foq

我想用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()

1 个答案:

答案 0 :(得分:3)

Foq支持退货:单位 - &gt; '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