惩戒与前pression&LT方法; Func键< T,布尔>>使用起订量参数布尔、参数、方法、LT

2023-09-04 02:46:08 作者:狂澜

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

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; 参数约束