Setup and verify expression with Moq

后端 未结 1 1141
天涯浪人
天涯浪人 2021-01-05 17:15

Is there a way to setup and verify a method call that use an Expression with Moq?

The first attempt is the one I would like to get it to work, while the second one i

相关标签:
1条回答
  • 2021-01-05 17:45

    The following code demonstrates how to test in such scenarios. The general idea is that you execute the passed in query against a "real" data. That way, you don't even need "Verify", as if the query is not right, it will not find the data.

    Modify to suit your needs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using Moq;
    using NUnit.Framework;
    
    namespace StackOverflowExample.Moq
    {
        public class Product
        {
            public string UrlRewrite { get; set; }
            public string Title { get; set; }
        }
    
        public interface IProductQuery
        {
            Product GetByFilter(Expression<Func<Product, bool>> filter);
        }
    
        public class Controller
        {
            private readonly IProductQuery _queryProvider;
            public Controller(IProductQuery queryProvider)
            {
                _queryProvider = queryProvider;
            }
    
            public Product GetProductByUrl(string urlRewrite)
            {
                return _queryProvider.GetByFilter(x => x.UrlRewrite == urlRewrite);
            }
        }
    
        [TestFixture]
        public class ExpressionMatching
        {
            [Test]
            public void MatchTest()
            {
                //arrange
                const string GOODURL = "goodurl";
                var goodProduct = new Product {UrlRewrite = GOODURL};
                var products = new List<Product>
                    {
                        goodProduct
                    };
    
                var qp = new Mock<IProductQuery>();
                qp.Setup(q => q.GetByFilter(It.IsAny<Expression<Func<Product, bool>>>()))
                  .Returns<Expression<Func<Product, bool>>>(q =>
                      {
                          var query = q.Compile();
                          return products.First(query);
                      });
    
                var testController = new Controller(qp.Object);
    
                //act
                var foundProduct = testController.GetProductByUrl(GOODURL);
    
                //assert
                Assert.AreSame(foundProduct, goodProduct);
            }
        }
    } 
    
    0 讨论(0)
提交回复
热议问题