Is there a way to set up and test a call to a method that uses an expression using Moq?
The first attempt is that I would like to make it work, and the second is a “patch” so that the Assert part works (while the verification part still did not work)
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()); }
The test test fails with an Assert error and throws a null reference exception because the GetByFilter method is never called.
If instead I use this
[Setup] public void SetUp() { productsQuery.Setup(x => x.GetByFilter(It.IsAny<Expression<Func<Product, bool>>>())).Returns(new Product() { Title = "Good product", ... }); }
The test passes part of Assert, but this time Verify, which does not say that it is never called.
Is there a way to customize a method call with a specific expression instead of using the generic It.IsAny<>() ?
Update
I also tried Ufuk Hacıoğulları's suggestion in the comments and created the following
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()); }
But I get a null reference exception, as in the first attempt.
The code in my controller is as follows
public ActionResult Detail(string urlRewrite) {
c # moq
Iridio
source share