Rhino Stub不使用Arg.Is.Equal

问题描述 投票:0回答:1

我有一个方法,以对象作为参数

方法签名

  IEnumerable<TResult> ExecuteSql<TResult>(string sql, object param)

方法调用

   string query ="select * from table";
   var data = _Executor.ExecuteSql<ObjectToReturn>(query,
                    new
                    {
                        CustomerID = customerId,
                        AnotherId1= id2,
                        AnotherId2 = id3
                    });

单元测试

使用下面的示例1模拟它不起作用(不返回存根返回对象。)

1

 _procExecutor.Stub(x => x.ExecuteSql<ObjectToReturn>(Arg<string>.Is.Anything,
                Arg<object>.Is.Equal(new
                {
                    CustomerID = customerId,
                    AnotherId1 = 10,
                    AnotherId2 = 11
                }))).Return(new List<ObjectToReturn>() { new ObjectToReturn() { id = 100 } });      

这工作(确实返回存根返回对象。)

2

_procExecutor.Stub(x => x.ExecuteSql<ObjectToReturn>(Arg<string>.Is.Anything,
                Arg<object>.Is.Anything)).Return(new List<ObjectToReturn>() { new ObjectToReturn() { id = 100 } });     

但我想确保将正确的参数传递给正确的字段,因此我将方法存储为#1,但它不会返回存根返回对象。

我在示例1中做错了什么?

c# unit-testing rhino-mocks
1个回答
0
投票

问题是匿名arg你可以像这样的例子使用Matches:

IUrlProvider urlProvider = MockRepository.GenerateStub<IUrlProvider>();

urlProvider.Stub(u => u.Action(
    Arg<string>.Is.Equal("ValidateCode"),
    Arg<object>.Matches(new PropertiesMatchConstraint(new { code = "spam-and-eggs" })) ))
    .Return("");

public class PropertiesMatchConstraint : AbstractConstraint
{
    private readonly object _equal;

    public PropertiesMatchConstraint(object obj)
    {
        _equal = obj;
    }

    public override bool Eval(object obj)
    {
        if (obj == null)
        {
            return (_equal == null);
        }
        var equalType = _equal.GetType();
        var objType = obj.GetType();
        foreach (var property in equalType.GetProperties())
        {
            var otherProperty = objType.GetProperty(property.Name);
            if (otherProperty == null || property.GetValue(_equal, null) != otherProperty.GetValue(obj, null))
            {
                return false;
            }
        }
        return true;
    }

    public override string Message
    {
        get
        {
            string str = _equal == null ? "null" : _equal.ToString();
            return "equal to " + str;
        }
    }
}

资源:

Arg<object>.Is.Equal with anonymous objects

© www.soinside.com 2019 - 2024. All rights reserved.