【发布时间】:2014-08-08 17:10:47
【问题描述】:
我对模拟的想法很陌生,我正在使用 Moq 对这段代码进行单元测试。
using Forum = ProForum.Domain.Database.tblForum;
using Thread = ProForum.Domain.Database.tblThread;
namespace ProForum.Domain.Concrete
{
public class ForumRepository : IForumRepository
{
protected Table<Forum> DataTable;
private ProForumDataContext dataContext;
public ForumRepository(ProForumDataContext dataContext)
{
DataTable = dataContext.GetTable<Forum>();
}
public Forum GetForumById(int id)
{
try
{
return DataTable.Single(f => f.tblForumID.Equals(id));
}
catch (Exception e)
{
return null;
}
}
}
}
我想测试GetForumById的方法。为此,我想创建 ProForumDataContext 的模拟并将模拟论坛插入其中。我应该如何为 ProForumDataContext 设置模拟,以便当我在其上调用 GetTable 方法时,它返回一个包含模拟论坛的表。表是System.Data.Linq.Table 类。
我正在做这样的事情:
[TestMethod]
public void Can_Get_Forum_ById()
{
//arrange
Mock<Forum> mockForum = new Mock<Forum>();
mockForum.Object.tblForumID = 1;
//Mock<Table<Forum>> tableMock = new Mock<Table<Forum>>();
//tableMock.Object.Attach(mockForum);
Mock<DiscussionForumDataContext> mockContext = new Mock<DiscussionForumDataContext>();
mockContext.Setup).
Returns();
}
我没有得到传递给设置的内容和返回的内容。 论坛类:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.tblForums")]
public partial class tblForum : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _tblForumID;
private string _Name;
private string _Description;
private int _tblUserLogin_ID;
private int _TotalPosts;
private int _TotalThreads;
private bool _Active;
private System.Data.Linq.Binary _RowVersion;
private System.DateTime _Modified;
private System.DateTime _Created;
private EntitySet<tblThread> _tblThreads;
public tblForum()
{
this._tblThreads = new EntitySet<tblThread>(new Action<tblThread>(this.attach_tblThreads), new Action<tblThread>(this.detach_tblThreads));
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_tblForumID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]
public int tblForumID
{
get
{
return this._tblForumID;
}
set
{
if ((this._tblForumID != value))
{
this.OntblForumIDChanging(value);
this.SendPropertyChanging();
this._tblForumID = value;
this.SendPropertyChanged("tblForumID");
this.OntblForumIDChanged();
}
}
}
【问题讨论】:
标签: c# linq unit-testing moq