Taunts a class with an explicitly implemented interface using Foq

I wanted to make fun of a framework entity DbSetwith Foq . It looks something like this:

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 
    @>
)

I tried to force and cast xin IQueryablein some places, but this does not work.

As you can see here in the docs for DbSet, it implements the interface IQueryablethrough DbQuery, but does so by “explicitly” implementing the properties.

Is Moq , there is a function As, so you can tell it to be treated as IQueryable, which looks like this:

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

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())
+3

All Articles