I am writing unit tests for a repository that use System.Data.Linq DataConext object to get Table of entities from database. Here's the code :
public class ForumRepository : IForumRepository
{
protected Table<Forum> DataTable;
IDataContextWrapper DataContext;
public ForumRepository(IDataContextWrapper DataContext)
{
DataTable = DataContext.GetTable<Forum>();
}
public Forum GetForumById(int id)
{
try
{
return DataTable.Single(f => f.tblForumID.Equals(id));
}
catch(Exception e)
{
return null;
}
}
And here's the wrapper implemention :
public class DataContextWrapper<T> : IDataContextWrapper where T : EpixForumDataContext, new()
{
private readonly T db;
public DataContextWrapper()
{
var t = typeof(T);
db = (T)Activator.CreateInstance(t);
}
public DataContextWrapper(string connectionString)
{
var t = typeof(T);
db = (T)Activator.CreateInstance(t, connectionString);
}
public Table<TableName> GetTable<TableName>() where TableName : class
{
return (Table<TableName>)db.GetTable(typeof(TableName));
}
I want to test the repository method.
public class UnitTest1
{
[TestMethod]
public void Can_Get_Forum_ById()
{
//arrange
Forum dummyForum = new Forum() { tblForumID = 1};
Mock<ITable<Forum>> tableMock = new Mock<ITable<Forum>>();
tableMock.Object.Attach(dummyForum);
Mock<IDataContextWrapper> mock = new Mock<IDataContextWrapper>();
mock.Setup(m => m.GetTable<Forum>()).Returns(tableMock.Object) ;
//act
ForumRepository repos = new ForumRepository(mock.Object);
Forum resultForum = repos.GetForumById(1);
//assert
Assert.AreEqual(resultForum.tblForumID, 1);
Where Forum is an auto generated class. I want to setup the forum for Table so that when I do a GetTable on the ContextWrapper I get the table of forums. I do not know if Table.Attach would attach the Forum to the Table or not. Also when I run the test it says
'Type to mock must be an interface or an abstract class or non-sealed class'.
Have I got it all wrong?