在做 ASP.NET 站点(例如 ASP.NET MVC 站点)时创建测试持久层的最佳实践是什么?
我见过的许多示例在单元测试项目中使用 Moq(或其他模拟框架),但我想像 .. moq 一样将我的持久层移除,以便我的网站显示数据和内容,但它不是来自数据库。我想最后这样做。我见过的所有 mock 的东西只存在于单元测试中。
当人们想要( stub ?)伪造一个持久层以进行快速开发时,他们会做什么实践?我使用依赖注入(inject)来处理它,并为我的持久层提供了一些硬编码的结果(这确实是手动且无聊的)。
其他人在做什么?示例和链接会很棒:)
更新
只是一点点更新:到目前为止,我从拥有一个假存储库和一个 SQL 存储库中获得了相当多的里程——每个类都实现了一个接口(interface)。然后,使用 DI(我使用的是 StructureMap),我可以在我的假存储库或 SQL 存储库之间切换。到目前为止,它运行良好:)
(想想我在将近 11 个月前问过这个问题也很可怕,从我现在编辑这个问题开始!)
最佳答案
假设您使用 Rob Conery 的 MVC Store Front 中的存储库模式:
http://blog.wekeroad.com/mvc-storefront/mvc-storefront-part-1/
我遵循了 Rob Conery 的教程,但遇到了和你一样的需求。最好的做法是将您创建的 Mock 存储库移动到一个名为 Mocks 的单独项目中,然后您可以在实例化服务时轻松地将它们替换为真实的。如果您喜欢冒险,您可以创建一个从配置文件中获取值的工厂,以实例化模拟或真实存储库,
例如
public static ICatalogRepository GetCatalogRepository(bool useMock)
{
if(useMock)
return new FakeCatalogRepository();
else
return new SqlCatalogRepository();
}
或使用依赖注入(inject)框架:)
container.Resolve<ICatalogRepository>();
祝你好运!
编辑:在回应您的评论时,听起来您想使用列表和 LINQ 来模拟数据库的操作,例如获取产品,存储产品。我以前做过。这是一个例子:
public class Product
{
public int Identity { get; set; }
public string Name { get; set; }
public string Description { get; set; }
//etc
}
public class FakeCatalogRepository()
{
private List<Product> _fakes;
public FakeCatalogCatalogRepository()
{
_fakes = new List<Product>();
//Set up some initial fake data
for(int i=0; i < 5; i++)
{
Product p = new Product
{
Identity = i,
Name = "product"+i,
Description = "description of product"+i
};
_fakes.Add(p);
}
}
public void StoreProduct(Product p)
{
//Emulate insert/update functionality
_fakes.Add(p);
}
public Product GetProductByIdentity(int id)
{
//emulate "SELECT * FROM products WHERE id = 1234
var aProduct = (from p in _fakes.AsQueryable()
where p.Identity = id
select p).SingleOrDefault();
return aProduct;
}
}
这是否更有意义?
关于asp.net - 进行 TDD 时如何最好地创建测试数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/286876/