Search code examples
c#.netentity-frameworkunit-testingjustmock

Entity Framework: Mocking with JustMock


I've just installed the Telerik.JustMock.EntityFramework package, and i am trying it.

I've tried this:

var ctx = EntityFrameworkMock.Create<MyDbContext>().PrepareMock();

var source = new List<MyEntity>()
            {
                new MyEntity(){ Description = "asd" },
                new MyEntity(){ Description = "asd2" },
            };

ctx.MyEntities.Bind(source);

And when i retrieve the data doing this, it works:

ctx.MyEntities.ToList();

But if i do the next:

ctx.Set<MyEntity>().ToList();

It returns an empty collection.

Do you know what i am doing wrong? Or do you know how can i mock the collection that my context returns? Because i am using the repository pattern and i want to test the methods from the repository, that is working with a given context.

Btw, this is my MyDbContext class:

public class MyDbContext : DbContext{
    public DbSet<MyEntity> MyEntities { get; set; }
}

Solution

  • Mocking a DbContext can be difficult because there are a lot of moving parts that the context is keeping up with. I've had success using a library that helps to set up an in-memory data context. Not exactly a direct answer, but I've run into lots of problems attempting a straight mock with other mocking frameworks

    http://effort.codeplex.com/

    This library is available as a nuget package.