【发布时间】:2015-04-01 11:11:38
【问题描述】:
在我的控制器操作中,每当添加新产品时,我都会在数据库中检查该产品编号是否不存在。此检查的代码如下所示
public ActionResult Index(ProductModel model)
{
var productCount = _productsService.GetAll(true).Count(x => x.ProductNumber == model.ProductNumber);
if (productCount > 0)
ModelState.AddModelError("ProductNumber", Product already present in the system!");
// more processing
}
我是 MOQ 测试的新手,我正在尝试编写一个单元测试来设置 GetAll 方法,该方法将返回 0。我写过类似的东西,但它似乎不起作用
var _productsService = new Mock<IProductsService>();
_productsService.Setup(m => m.GetAll(true).Count()).Returns(0);
有什么想法吗?谢谢
【问题讨论】:
-
您要测试的功能究竟是什么?控制器方法还是 _productsService.GetAll()?
-
@greenhoorn 我想测试控制器动作,但在这个动作中我调用 GetAll 方法我需要设置它并获取一个值。
-
您遇到错误了吗?
-
System.NotSupportedException : 表达式引用了不属于模拟对象的方法:m => m.GetAll(True).Count
() -
方法'GetAll'是什么样子的?
标签: c# asp.net-mvc unit-testing moq