Moq对IRepository传递表达式的期望 [英] Moq Expect On IRepository Passing Expression

查看:61
本文介绍了Moq对IRepository传递表达式的期望的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来验证我正在测试的方法的行为:

I am using this code to verify a behavior of a method I am testing:

    _repository.Expect(f => f.FindAll(t => t.STATUS_CD == "A"))
    .Returns(new List<JSOFile>())
    .AtMostOnce()
    .Verifiable();

_repository定义为:

_repository is defined as:

private Mock<IRepository<JSOFile>> _repository;

运行测试时,出现此异常:

When my test is run, I get this exception:

表达式t =>(t.STATUS_CD ="A")不受支持.

如果不能将表达式传递到Expect方法中,有人可以告诉我如何测试这种行为吗?

Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?

谢谢!

推荐答案

这有点作弊.我对表达式执行.ToString()并进行比较.这意味着您必须在测试的类中以相同的方式编写lambda.如果需要,您可以在此时进行一些解析

This is a bit of a cheaty way. I do a .ToString() on the expressions and compare them. This means you have to write the lambda the same way in the class under test. If you wanted, you could do some parsing at this point

    [Test]
    public void MoqTests()
    {
        var mockedRepo = new Mock<IRepository<Meeting>>();
        mockedRepo.Setup(r => r.FindWhere(MatchLambda<Meeting>(m => m.ID == 500))).Returns(new List<Meeting>());
        Assert.IsNull(mockedRepo.Object.FindWhere(m => m.ID == 400));
        Assert.AreEqual(0, mockedRepo.Object.FindWhere(m => m.ID == 500).Count);
    }

    //I broke this out into a helper as its a bit ugly
    Expression<Func<Meeting, bool>> MatchLambda<T>(Expression<Func<Meeting, bool>> exp)
    {
        return It.Is<Expression<Func<Meeting, bool>>>(e => e.ToString() == exp.ToString());
    }

这篇关于Moq对IRepository传递表达式的期望的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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