惩戒与前pression&LT方法; Func键< T,布尔>>使用起订量参数 [英] Mocking methods with Expression<Func<T,bool>> parameter using Moq

查看:157
本文介绍了惩戒与前pression&LT方法; Func键< T,布尔>>使用起订量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想嘲笑起订量使用该接口

I want to mock this interface using Moq

IInterfaceToBeMocked {
IEnumerable<Dude> SearchDudeByFilter(Expression<Func<Dude,bool>> filter);
}

我的想法做一些像

I was thinking of doing something like

_mock.Setup(method => method.SearchDudeByFilter( x=> x.DudeId.Equals(10) && X.Ride.Equals("Harley"))). Returns(_dudes);// _dudes is an in-memory list of dudes.

当我尝试调试单元测试,我需要这种嘲讽,它说,前pression是不允许的指向的lambda。如果让我现在用的xUnit的测试框架的任何差异。

When I try to debug the unit test where i need this mocking, it says that "expression is not allowed" pointing towards the lambda. If it makes any difference I am using xUnit as the testing framework.

推荐答案

以下工作正常,我用的起订量4.0测试版

The following works fine for me with the Moq 4.0 Beta:

public class Dude 
{
    public int DudeId { get; set; }
    public string Ride { get; set; }
}

public interface IInterfaceToBeMocked 
{
    IEnumerable<Dude> SearchDudeByFilter(Expression<Func<Dude,bool>> filter);
}

和单元测试:

[TestMethod]
public void TestDudes()
{
    // arrange
    var expectedDudes = new[]
    {
        new Dude(), new Dude()
    };
    var mock = new Mock<IInterfaceToBeMocked>();
    mock.Setup(method => method.SearchDudeByFilter(
        x => x.DudeId.Equals(10) && x.Ride.Equals("Harley"))
    ).Returns(expectedDudes);

    // act
    // Remark: In a real unit test this call will be made implicitly
    // by the object under test that depends on the interface
    var actualDudes = mock.Object.SearchDudeByFilter(
        x => x.DudeId.Equals(10) && x.Ride.Equals("Harley")
    );

    // assert
    Assert.AreEqual(actualDudes, expectedDudes);
}

现在,如果你改变的东西转化为实际的方法的参数调用测试将不再通过,因为嘲笑的方法将返回预期的结果仅当参数是相同的:

Now if you change something into the argument of actual method call the test will no longer pass because the mocked method will return the expected result only if the argument is the same:

var actualDudes = mock.Object.SearchDudeByFilter(
    x => x.DudeId.Equals(20) && x.Ride.Equals("Honda")
);

注:即以lambda EX pressions嘲讽的方法是,是不是在previous版本,我们需要利用现有的一个新特性 It.Is&LT; SOMETYPE&GT; It.IsAny&LT; SOMETYPE&GT; 参数约束

这篇关于惩戒与前pression&LT方法; Func键&LT; T,布尔&GT;&GT;使用起订量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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