【问题标题】:Can you set up recursive mocks in foq?你能在 foq 中设置递归模拟吗?
【发布时间】:2013-04-24 04:55:56
【问题描述】:

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

【问题讨论】:

    标签: f# mocking easynetq foq


    【解决方案1】:

    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
    

    【讨论】:

    • 太棒了!谢谢@Phillip Trelford。不敢相信我没有注意到单位 -> 'TValue 过载。
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多