How to mimic System.Data.Linq.Table <MyClass>
One of my base repository classes contains a method:
public abstract class RepositoryBase<T, TDb> : IRepository<T> where T : IEntity where TDb : class, IDbEntity, new() { protected internal abstract Table<TDb> GetTable(); ... } I am writing unit test for a derived repository class that contains an implementation of the mentioned method:
public class CmOptionRepository : RepositoryBase<ICmOption, CMCoreDAL.DbData.CMOption>, ICmOptionRepository { protected internal override System.Data.Linq.Table<CMCoreDAL.DbData.CMOption> GetTable() { return Context.CMOptions; } .... } Here: Context is the DB Linq model, CMOptions is one of the DB tables.
I want my GetTable () method to return a special data set.
I am going to make fun of the method:
System.Data.Linq.Table<CMCoreDAL.DbData.CMOption> table = ...; Mock<CmOptionRepository> mockRepository = new Mock<CmOptionRepository>(MockBehavior.Strict); mockRepository.Setup(mock => mock.GetTable()).Returns(table); But I donβt know how to instantiate the System.Data.Linq.Table<CMCoreDAL.DbData.CMOption> class.
Question: how can I mock System.Data.Linq.Table<> ? Or maybe I need to change the method signature to avoid using the System.Data.Linq.Table<> class?
Please inform. Any thoughts are welcome.
PS I am using Moq.
If you are using .NET 4.0, Table<T> implements ITable<T> so that you use the ITable<TDb> interface in the ITable<TDb> return type instead of the specific type. Then you can brush it off.
In .NET 3.5, this is a bit more complicated because Table<T> implements only ITable (not generic).
You should not expand Table<T> outside your repository unless there is an explicit need to perform operations on an instance of Table<T> . Instead, return the IQueryable<T> to your repository, which is easier to make fun of. If you need to upgrade, you can return ITable<T> .
I think here is the solution:
Copy data:
IUnityContainer container = new UnityContainer(); Mock<IDataContext> mockDataContext = new Mock<IDataContext>(); container.RegisterInstance(mockDataContext.Object); CmOptionRepository mockRepository = new CmOptionRepository(container);Layout of the returned table:
Mock<System.Data.Linq.Table<CMCoreDAL.DbData.CMOption>> mockTable = new Mock<System.Data.Linq.Table<CMCoreDAL.DbData.CMOption>>(); mockDataContext.Setup(mock => mock.CMOptions).Returns(mockTable.Object);Functionality of the Mock "table" object:
mockTable .Setup(mock => mock.Select( It.IsAny<Func<CMCoreDAL.DbData.CMOption, ICmOption>>() )) .Returns(options);
Honestly, I'm not sure that it will work, it will be checked tomorrow, but now it is at least compiled.
Give up the data access code and use the repository template.