开发者

MVC moq with repository that uses lambda expression

I have a controller method that acceses a repository method which has lambda expression as parameter:

// GET: /Product/
    public ViewResult List(string category, int page = 1) {

        ProductsListViewModel productsListViewModel = new ProductsListViewModel {
            Products = _repository.GetByPage(q => q.Category == category || category == null, page, PageSize),
            PagingInfo = new PagingInfo {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = _repository.Get(q=>q.Category==category || category==null).Count()
            },
            CurrentCategory = category
        };

        return View(productsListViewModel);
    }

In my unit test, when controller invokes the repository method, returned object("result" variable) is always null, do you have any idea about this situation?

public void Can_Paginate() {
        //Arrange
        //Cre开发者_JAVA百科ate mock repository
        Mock<IProductRepository> mock = new Mock<IProductRepository>();
        mock.Setup(q => q.GetByPage(c=>c.Category=="C1",1,3)).Returns(new List<Product>
                                                {
                                                    new Product {Id = 1, Name = "P1", Category = "C1"},
                                                    new Product {Id = 2, Name = "P2", Category = "C1"},
                                                    new Product {Id = 3, Name = "P3", Category = "C1"}
                                                });
        mock.Setup(q => q.Get(c => c.Category == "C1")).Returns(new List<Product>
                                                {
                                                    new Product {Id = 1, Name = "P1", Category = "C1"},
                                                    new Product {Id = 2, Name = "P2", Category = "C1"},
                                                    new Product {Id = 3, Name = "P3", Category = "C1"}
                                                });
        //Create a controller and make page size 3 items
        ProductController controller = new ProductController(mock.Object);
        controller.PageSize = 3;

        //Action
        ProductsListViewModel result = (ProductsListViewModel) controller.List("C1", 1).Model;

        //Assert
        Assert.IsTrue(result.Products.Count()==3);
    }

Thanks


Just had quick look at the moq wiki and it had an example of matching Func<int>

as a parameter. So to match an argument of Func<string> you would write something like this:

mock.Setup(q => q.GetByPage(It.Is<string>(c=>c.Category=="C1"),1,3)).Returns...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜