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.