Pur*_*ome 17 asp.net tdd persistence dependency-injection mocking
在执行ASP.NET站点(例如ASP.NET MVC站点)时创建测试持久层的最佳实践是什么?
我见过的很多例子都在单元测试项目中使用了Moq(或其他模拟框架),但我想,像moq我的持久层,以便我的网站显示数据和内容,但它不是来自数据库.我想做到最后.我见过的所有嘲弄的东西只存在于单元测试中.
当人们想要(stub?)伪造一个持久层来快速快速开发时,人们会采取什么样的做法?我使用依赖注入来处理它,并为我的持久层提供一些硬编码结果(这实际上是手动和无聊的).
其他人在做什么?示例和链接会很棒:)
只是一点点更新:到目前为止,我已经获得了一个假的存储库和一个SQL存储库 - 每个类实现一个接口.然后,使用DI(我正在使用StructureMap),我可以在我的虚拟存储库或SQL存储库之间切换.到目前为止,它运作良好:)
(也是可怕的想到我差不多11个月前问过这个问题,从我编辑这个问题开始,现在!)
假设您正在使用 Rob Conery 的 MVC Store Front 中的存储库模式:
http://blog.wekeroad.com/mvc-storefront/mvc-storefront-part-1/
我遵循了 Rob Conery 的教程,但遇到了和你一样的需求。最好的办法是将您创建的模拟存储库移动到一个名为 Mocks 的单独项目中,然后在实例化服务时可以轻松地将它们与真实的存储库交换。如果您喜欢冒险,您可以创建一个工厂,从配置文件中获取值来实例化模拟或真实存储库,
例如
public static ICatalogRepository GetCatalogRepository(bool useMock)
{
if(useMock)
return new FakeCatalogRepository();
else
return new SqlCatalogRepository();
}
Run Code Online (Sandbox Code Playgroud)
或使用依赖注入框架:)
container.Resolve<ICatalogRepository>();
Run Code Online (Sandbox Code Playgroud)
祝你好运!
编辑:为了回应您的评论,听起来您想使用列表和 LINQ 来模拟数据库的操作,例如 GetProducts、StoreProduct。我以前做过这个。这是一个例子:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这更有意义吗?
| 归档时间: |
|
| 查看次数: |
1209 次 |
| 最近记录: |