Compartir en:

Some people might discuss that mocking the Data Layer can be useless, but sometimes our database operations are simple enough we do not want to incur in the costly job of setting up a real database for our tests or just because our logic needs testing by itself and we want to keep it simple and fast without adding too much distraction on setting things up.

How?

There are a LOT of blog posts teaching about how to mock Entity Framework context, but most of them try to re implement their own version of a fake IDbSet. I just wanted something to reduce the amount of work to the minimun to start testing what I really needed to test.

I decided to use MS Fakes framework because it solves a lot of hard work on creating mock objects. But unluckily, stubbing the IDbSet interface of Entity Framework using Fakes can be really painful. You can’t just fake 1 or 2 methods, you’ll need to fake probably all of them.

So I found FakeDbSet nuget package which provides an in-memory implementation of the IDbSet interface, allowing you to mocking your context really quickly.

Let’s see an example

Say your database context is like the following:

namespace Sample
{
  public class DatabaseContext : DBContext
  {
     IDbSet Users { get; set; }
     IDbSet Photos { get; set; }

     //Our implementation
  }

  public class DatabaseContextFactory
  {
     public static DatabaseContext Create()
     {
        return new DatabaseContext();
     }
  }
}

You just need to create a Fakes assembly of the one containing DatabaseContext and you can build a Stub of that class, creating an “in memory” Stub context.

[Fact]
public void TestEditLatestPhoto()
{
  var mockDbContext =
     new Sample.Fakes.StubDatabaseContext()
     {
        Users = new InMemoryDbSet(true);
        Photos = new InMemoryDbSet(true);
        SaveChanges01 = () => { return 0; }
     }

  var mockDbContextFactory =
     new Sample.Fakes.StubDatabaseContext()
     {
       Create = () => { return mockDbContext; }
     }

  int photoId = 1;
  mockDbContext.Photos.Add(
            CreateFakePhoto("userA", photoId) );

  PhotoEditor editor =
            new PhotoEditor(mockDbContextFactory);
  editor.EditLatestPhoto("userA");

  //Asserts
  // ...
}

And voilà! You can even assert over entities saved by the test in the fake database.

  • Jesica Fera

    R&D Engineer

    Jesica discovered she wanted to be a Computer Engineer at the age of 13, with a basic knowledge of HTML, Visual Basic and Pascal. Since then, she loves exploring and learning new technologies, specially innovations in computational linguistics, data mining and AI. Besides computers, Jesica enjoys spending her time in other passions: figure skating,

  • Antonio Riga April 11th, 2014 at 4:44 PM

    Thanks a lot!

Dejar un comentario