有没有办法设置和验证使用带 Moq 的表达式的方法调用?
第一次尝试是我想让它工作的尝试,而第二次尝试是让Assert
部件工作的“补丁”(验证部分仍然失败)
string goodUrl = "good-product-url";
[Setup]
public void SetUp()
{
productsQuery.Setup(x => x.GetByFilter(m=>m.Url== goodUrl).Returns(new Product() { Title = "Good product", ... });
}
[Test]
public void MyTest()
{
var controller = GetController();
var result = ((ViewResult)controller.Detail(goodUrl)).Model as ProductViewModel;
Assert.AreEqual("Good product", result.Title);
productsQuery.Verify(x => x.GetByFilter(t => t.Url == goodUrl), Times.Once());
}
测试失败Assert
并抛出空引用异常,因为 GetByFilter 方法从未被调用。
如果相反我使用这个
[Setup]
public void SetUp()
{
productsQuery.Setup(x => x.GetByFilter(It.IsAny<Expression<Func<Product, bool>>>())).Returns(new Product() { Title = "Good product", ... });
}
测试通过了 Assert 部分,但这次是 Verify that fail,表示它永远不会被调用。
有没有办法使用特定表达式而不是使用泛型来设置方法调用It.IsAny<>()
?
更新
我还在评论中尝试了Ufuk Hacıoğulları的建议,并创建了以下内容
Expression<Func<Product, bool>> goodUrlExpression = x => x.UrlRewrite == "GoodUrl";
[Setup]
public void SetUp()
{
productsQuery.Setup(x => x.GetByFilter(goodUrlExpression)).Returns(new Product() { Title = "Good product", ... });
}
[Test]
public void MyTest()
{
...
productsQuery.Verify(x => x.GetByFilter(goodUrlExpression), Times.Once());
}
但是我得到了一个空引用异常,就像第一次尝试一样。
我的控制器中的代码如下
public ActionResult Detail(string urlRewrite)
{
//Here, during tests, I get the null reference exception
var entity = productQueries.GetByFilter(x => x.UrlRewrite == urlRewrite);
var model = new ProductDetailViewModel() { UrlRewrite = entity.UrlRewrite, Culture = entity.Culture, Title = entity.Title };
return View(model);
}