user176504
user176504

Reputation: 313

Mocking with Entity Framework and TypeMock

I'm having real problems with mocking when it comes to EF (version 6, for what it's worth).

This is the method I am trying to test:

    public async Task<bool> IsSurveyComplete(Guid entityRef)
    {
        using (MyDbEntities context = new MyDbEntities())
        {
            MyEntity entity = await context.MyEntities.FindAsync(entityRef);
            // do stuff
        }
    }

I need to fake "entity", but I realised that just trying to do Isolate.Fake.Instance doesn't work, since it's actually an ObjectProxy rather than an instance of type MyEntity. I discovered that the way to get around this was to set the context.Configuration.ProxyCreationEnabled to false. However, this doesn't work if I do it anywhere except in the constructor. If I try to fake the DbContextConfiguration, it still uses proxies.

So, I created a new constructor to be used when testing:

    public MyDbEntities(bool useProxy)
        : base("name=MyDbEntities")
    {
        this.Configuration.ProxyCreationEnabled = useProxy;
    }

and then, in my test:

    Isolate.WhenCalled(() => new MyDbEntities()).WillReturn(new MyDbEntities(false));

However, the ProxyCreationEnabled property is still set to true when I put a breakpoint in the IsSurveyComplete method after the using statement.

I also tried (among many, many other things):

    var fakeContext = new MyDbEntities(false);
    Isolate.Swap.AllInstances<MyDbEntities>().With(fakeContext);

Again, when I investigate with a breakpoint, ProxyCreationEnabled is true.

I'm about to give up on TypeMock!

Upvotes: 1

Views: 121

Answers (1)

Daniel
Daniel

Reputation: 174

declaimer: i'm working in typemock

you are using a wrong function of typemock, you should use:

var fakeContext = Isolate.fake.NextInstance<MyDbEntities>();
Isolate.whenCalled(()=>fakeContext.MyEntities).
   WillReturnCollectionValuesOf(listOfEntities.AsQueryable());

instead of:

var fakeContext = new MyDbEntities(false); Isolate.Swap.AllInstances<MyDbEntities>().With(fakeContext);

Upvotes: 2

Related Questions