Be careful when using mocked repository

One of the software development best practices is to use interfaces and dependency injection. But be careful when using a mocked version of your repository.

With FakeDbSet an InMemory IDbSet can be created for unit testing purposes. During setup you’d add the records and the test will simply use those records. But there is a small difference with the actual Entity Framework implementation used with most applications: reading from the database will result in a new object.

The properties of the object will be the same, no matter how often you’d get it, but it is a new object. During integration testing I noticed some strange behaviour due to this. Changes made to the object by my business logic would disappear.

Extra utils used are the Fakes generated by Visual Studio and the Copy extension from github. In my code I changed the setup of the test repository to mimic this behaviour:

private IRepository CreateFakeRepository(object[] records) {
   var fakeRepository = new Fakes.StubIRepository();
   fakeRepository.RecordsGet = () => {
      var fakeDataSet = new FakeDbSet.InMemoryDbSet(true);
      foreach (var record in records) {
         fakeDataSet.Add(record.Copy());
      }
      return fakeDataSet;
   };
   return fakeRepository;
}

After this half (!) my unit tests turned red. Fixing it took some time, but I’m more confident about the business logic now.

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Test and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s