使用 Foq 模拟具有显式实现接口的类

alb*_*jan 5 c# f# entity-framework mocking foq

我想DbSet使用Foq模拟一个实体框架。它是这样的:

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 wrong. x doesn't have a property Provider
        x.Provider --> patients.Provider 
    @>
)
Run Code Online (Sandbox Code Playgroud)

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

正如你可以看到这里的文档为DbSet它确实实现了IQueryable通过接口DbQuery,而是通过“明确的”执行属性这样做。

Moq是否有一个函数,As所以你可以告诉它把它当作一个IQueryable看起来像:

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

Phi*_*ord 5

Foq 的最新版本(1.7)现在支持使用一种Mock.As方法实现多个接口,类似于 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())
Run Code Online (Sandbox Code Playgroud)