Moq.Mock T -如何设置采用表达式的方法 [英] Moq.Mock<T> - how to set up a method that takes an expression

查看:102
本文介绍了Moq.Mock T -如何设置采用表达式的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在模拟我的存储库接口,不确定如何设置采用表达式并返回对象的方法?我正在使用Moq和NUnit.

I am Mocking my repository interface and am not sure how to set up a method that takes an expression and returns an object? I am using Moq and NUnit.

接口:

public interface IReadOnlyRepository : IDisposable
{
    IQueryable<T> All<T>() where T : class;
    T Single<T>(Expression<Func<T, bool>> expression) where T : class;
}

已使用IQueryable进行测试,但不知道如何设置T Single:

Test with IQueryable is already set up, but don't know how to set up the T Single:

private Moq.Mock<IReadOnlyRepository> _mockRepos;
private AdminController _controller;
[SetUp]
public void SetUp()
{
    var allPages = new List<Page>();
    for (var i = 0; i < 10; i++)
    {
        allPages.Add(new Page { Id = i, Title = "Page Title " + i, Slug = "Page-Title-" + i, Content = "Page " + i + " on page content." });
    }
    _mockRepos = new Moq.Mock<IReadOnlyRepository>();
    _mockRepos.Setup(x => x.All<Page>()).Returns(allPages.AsQueryable());
    //Not sure what to do here???
    _mockRepos.Setup(x => x.Single<Page>()
    //----
    _controller = new AdminController(_mockRepos.Object);
}

推荐答案

您可以这样设置:

_mockRepos.Setup(x => x.Single<Page>(It.IsAny<Expression<Func<Page, bool>>>()))//.Returns etc...;

但是,您遇到了Moq的缺点之一.您可能希望在其中放置一个实际的表达式而不是使用It.IsAny,但是Moq不支持设置采用带有特定表达式的表达式的方法(这是很难实现的功能).困难来自必须弄清楚两个表达式是否相等.

However you are coming up against one of Moq's shortcomings. You would want to put an actual expression there instead of using It.IsAny, but Moq doesn't support setting up methods that take expressions with specific expressions (it's a difficult feature to implement). The difficulty comes from having to figure out whether two expressions are equivalent.

因此,在测试中,您可以传入 any Expression<Func<Page,bool>>,并且无论您设置了要返回的模拟内容,它都会传回.测试的价值略有稀释.

So in your test you can pass in any Expression<Func<Page,bool>> and it will pass back whatever you have setup the mock to return. The value of the test is a little diluted.

这篇关于Moq.Mock T -如何设置采用表达式的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆