我想测试一些代码,为了实现这一点,我需要伪造 DAL ( Entity Framework 6 - Code first
) 中定义的 DbContext。它大部分进展顺利,但是当数据模型类使用该TypeName
属性时我遇到了一个问题。我做了一个骨架来演示这个问题。
数据模型:
[Table("Customer")]
public class Customer
{
[Key]
public int Id { get; set; }
public string FirstName{ get; set; }
public string LastName { get; set; }
//this line causes the exception
[Column(TypeName = "money")]
public decimal Salary { get; set; }
}
上下文定义
public class MyDbContext : DbContext
{
public MyDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
public MyDbContext(DbConnection connection) : base(connection, true)
{
}
public IDbSet<Customer> Customers { get; set; }
}
还有一个用一些数据生成假上下文的虚拟方法:
private MyDbContext GenerateFakeDbContext()
{
var connection = DbConnectionFactory.CreateTransient();
var context = new MyDbContext(connection);
var customer = new Customer
{
Id = 1,
FirstName = "X",
LastName = "Y",
Salary = 1000
};
//this line throws the exception
context.Customers.Add(customer);
return context;
}
问题是TypeName
属性。当它被注释掉时,测试通过。但是如果它被启用,我会被System.InvalidOperationException
抛出,说
序列不包含匹配元素
总结一下,我的问题是:
- 即使数据模型类具有属性,有没有一种方法可以在测试中使用 Effort
- 如果没有,我应该采用什么替代方法来创建假 DbContext?