Edit: I forgot to mention that I'm using a Code First approach
I'm currently developing an application which uses the Entity Framework. The system currently has restaurants (Called Subjects in my code), users and reviews.
I'm brand new to using the Entity Framework, so I was wondering on how I can set up unit tests correctly. I'm assuming I don't have to test any inserting, retrieving and modifying data coming from EF, since this is probably tested already. When I want to set up tests for the code I'm writing, how should I handle objects coming from EF?
I'll give an example of a unit test I have developed. I'm using a repository structure for calls to the database. I'm aware this isn't necessary, but I like the abstraction in case we're switching databases.
My repository looks like this. (The user repository basically follows the same idea)
public class SubjectRepository
private readonly RecommenderContext _context;
_context = new RecommenderContext();
public Subject FindByGuid(Guid subjectId)
return _context.Subjects.Where(x => x.Id == subjectId).FirstOrDefault();
public void AddFollower(User userFollowing, Subject subjectToFollow)
_context.Subjects.Where(x => x.Id == subjectToFollow.Id).FirstOrDefault().Followers.Add(userFollowing);
public void CreateSubject(Subject sub)
public class SubjectRepositoryTests
public void init()
_subjectRepository = new SubjectRepository();
_userRepository = new UserRepository();
public void AddFollower()
Subject restaurant = Subject.CreateRandomSubject(); //These functions return randomized objects used for testing
User activeUser = User.CreateRandomUser();
Assuming you are using codefirst...
I would avoid having the proper RecommenderContext with direct database calls in it used in the tests. Replace it with an interface inside your repositories, and create a fake implementation that can be injected into your repository for testing. Then you don't have to worry about leaving residue or connecting to the db in tests.
You can use one of the FakeDbSet classes to implement the test context. Effectively this would test your repository logic whilst ignoring the built in EF behaviour, and leave your test nicely isolated.