Mocking entity repository using Moq
If you have a repository class wich enables all CRUD methods on your entity you need a Mocking Library in order to unit test your repository. Without a Mocking Library your unit test will work with real data and that is something you don't want.
Example mocking an Entity Repository
The repository class:
public class Repository : IRepository { private ObjectContext database; public Repository() { database = new DWH_IntertEntities(); } public List GetLijst() where T: class { return database.CreateObjectSet().ToList(); } }
The repository interface
public interface IRepository { System.Collections.Generic.List GetLijst() where T : class; }
The method wich instantiates the mockup object
private IRepository Mockup; private void PopulateRepository(Mock mockRepos) { List filiaalen = new List (); for (int i = 0; i < 25; i++) { filiaalen.Add( new Filialen(){ LidNr = i.ToString(), OndernemerNaam = i.ToString()}); } mockRepos.Setup(mr => mr.GetLijst()).Returns(filiaalen); Mockup = mockRepos.Object; }
A litle test method wich shows the mocked data in a datagrid :
public void Test(DataGridView datagridview) { var mockRepos = new Mock(); PopulateRepository(mockRepos); datagridview.DataSource = Mockup.GetLijst(); }