【发布时间】:2017-07-19 09:19:39
【问题描述】:
我的任务是创建一个测试脚本,该脚本将(使用实体框架)在表中查找值(如果存在)。
我必须使用的代码有这个构造函数:
public PostProductHelper(
Func<IMachineDBContext> contextFactory )
{
_contextFactory = contextFactory;
}
我的单元测试方法可能是这样的:
public string CheckAndRemoveProductNameFileExtIfExists(
string productName )
{
using ( var ctx = CreateContext() )
{
return ctx.Products.FirstOrDefault( d => d.Name == productName);
}
}
所以,通过谷歌搜索时的示例,我应该这样做:
MockProductRepository = Substitute.For<IProductRepository>();
MockMessagePublicationService = Substitute.For<IMessagePublicationService>();
MockMachineDBContext = Substitute.For<IMachineDBContext>(););
var Products = new List<Product>
{
new Product { Name = "BBB" },
new Product { Name = "ZZZ" },
new Product { Name = "AAA" },
}.AsQueryable();
MockMachineDBContext.Products.AddRange( Products );
但为了传递给我的构造函数,我必须将其修改为:
MockProductRepository = Substitute.For<IProductRepository>();
MockMessagePublicationService = Substitute.For<IMessagePublicationService>();
MockMachineDBContext = Substitute.For<Func<IMachineDBContext>>();
var Products = new List<Product>
{
new Product { Name = "BBB" },
new Product { Name = "ZZZ" },
new Product { Name = "AAA" },
}.AsQueryable();
MockMachineDBContext.Products.AddRange( Products );
最后一行显示“无法解析符号“产品”的哪些错误。
我不允许更改此构造函数,但我很感激我可能会犯一些错误。
【问题讨论】:
标签: c# entity-framework unit-testing nsubstitute