C# 使用Moq从Linq到SQL的模拟DataContext
我正在编写一个单元测试来模拟数据上下文中的System.Data.Linq.Table。我的代码如下,请在下面找到数据上下文、实体和单元测试。代码未编译,表示无法解析该方法。如何将此代码更改为格式良好的测试C# 使用Moq从Linq到SQL的模拟DataContext,c#,unit-testing,linq-to-sql,moq,C#,Unit Testing,Linq To Sql,Moq,我正在编写一个单元测试来模拟数据上下文中的System.Data.Linq.Table。我的代码如下,请在下面找到数据上下文、实体和单元测试。代码未编译,表示无法解析该方法。如何将此代码更改为格式良好的测试 [global::System.Data.Linq.Mapping.DatabaseAttribute(Name = "MyDB")] public partial class Table1DataContext : System.Data.Linq.DataContext { pr
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name = "MyDB")]
public partial class Table1DataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
partial void OnCreated();
public Table1DataContext() :
base(global::Properties.Settings.Default.DBConnectionString, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<Table1Definition> Table1Definitions
{
get
{
return this.GetTable<Table1Definition>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name = "dbo.Table1Definition")]
public partial class Table1Definition : INotifyPropertyChanging, INotifyPropertyChanged
{
private int _ID;
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_ID", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._ID = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
partial void OnIDChanging(int value);
partial void OnIDChanged();
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[TestClass]
public class TestClass
{
private Mock<Table1DataContext> dataContextMock;
[TestMethod]
public void ShoulReturnValidDefinition()
{
this.dataContextMock = new Mock<Table1DataContext>();
this.dataContextMock.SetupGet(x => x.Table1Definitions).Returns(GetFakeEntityDefinition());
}
private static IList<Table1Definition> GetFakeEntityDefinition()
{
return new List<Table1Definition> { new Table1Definition { ID = 1 } };
}
}
您能提供一个您尝试运行的测试的更好的示例吗?这里的测试并不是真正相关的,但在我的测试中,我需要模拟Table1定义的结果,以便我可以对另一项工作进行单元测试。我看到您将遇到的主要问题是,您试图用Moq模拟非虚拟成员。这将在运行测试时引发异常。您需要以某种方式抽象代码,无论是带有虚拟方法的抽象类还是接口。另一个选项是使用另一个模拟框架,该框架允许您模拟非虚拟成员。我只建议将其作为一个接口,因为这将导致更好的代码。即使我有一个抽象,我也需要用一个值替换System.Data.Linq.Table Table1定义,而这正是我正在努力解决的问题。