gpt4 book ai didi

c# - 使用 Foq 模拟具有显式实现接口(interface)的类

转载 作者:太空狗 更新时间:2023-10-30 01:34:59 25 4
gpt4 key购买 nike

我想使用 Foq 模拟一个 Entity Framework DbSet .它是这样的:

let patients = 
([
Patient(Guid "00000000-0000-0000-0000-000000000001");
Patient(Guid "00000000-0000-0000-0000-000000000002");
Patient(Guid "00000000-0000-0000-0000-000000000003");
]).AsQueryable()

let mockPatSet = Mock<DbSet<Patient>>.With(fun x ->
<@
// This is where things go wrong. x doesn't have a property Provider
x.Provider --> patients.Provider
@>
)

我尝试在某些地方将 x 强制转换为 IQueryable,但这不起作用。

如你所见hereDbSet 的文档中,它确实通过 DbQuery 实现了 IQueryable 接口(interface),但是通过“显式”实现属性来实现。

Moq有一个 Function As 所以你可以告诉它把它当作一个 IQueryable 看起来像:

var mockSet = new Mock<DbSet<Blog>>(); 
mockSet.As<IQueryable<Blog>>().Setup(m => m.Provider).Returns(data.Provider);

最佳答案

最新版本的 Foq ( 1.7 ),现在支持使用 Mock.As 方法实现多个接口(interface),类似于 Moq 中的设置,例如

type IFoo = 
abstract Foo : unit -> int

type IBar =
abstract Bar : unit -> int

[<Test>]
let ``can mock multiple interface types using setup`` () =
let x =
Mock<IFoo>().Setup(fun x -> <@ x.Foo() @>).Returns(2)
.As<IBar>().Setup(fun x -> <@ x.Bar() @>).Returns(1)
.Create()
Assert.AreEqual(1, x.Bar())
Assert.AreEqual(2, (x :?> IFoo).Foo())

关于c# - 使用 Foq 模拟具有显式实现接口(interface)的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com