C# 如何存根函数并为引用类型参数定义相等比较器

C# 如何存根函数并为引用类型参数定义相等比较器,c#,unit-testing,mocking,rhino-mocks,rhino,C#,Unit Testing,Mocking,Rhino Mocks,Rhino,我基本上想要存根一个函数,但是为引用类型参数定义我自己的相等比较器 我想存根一个函数来返回数据。我希望该方法的参数按特定值进行比较,而不是按ReferenceEquals进行比较。我也不想为我的参数引用类型创建等于重写。我认为下面是实现这一点的方法,但我收到了一个例外。有没有其他方法可以做到这一点和/或我在这里做错了什么 异常消息: System.Reflection.AmbiguousMatchException:找到不明确的匹配 public class Parameter

我基本上想要存根一个函数,但是为引用类型参数定义我自己的相等比较器

我想存根一个函数来返回数据。我希望该方法的参数按特定值进行比较,而不是按ReferenceEquals进行比较。我也不想为我的参数引用类型创建等于重写。我认为下面是实现这一点的方法,但我收到了一个例外。有没有其他方法可以做到这一点和/或我在这里做错了什么

异常消息: System.Reflection.AmbiguousMatchException:找到不明确的匹配

    public class Parameter
    {
        public string Property1 { get; set; }
    }

    public interface IStubbable
    {
         string DoStuff(Parameter param);
    }

    public class ThisService
    {
        private IStubbable _stubbable;
        public ThisService(IStubbable stubbable)
        {
            _stubbable = stubbable;
        }

        public string DoTheStuff(Parameter param)
        {
            return _stubbable.DoStuff(param);
        }
    }

    [Test]
    public void TestStubbing()
    {
        const string expectedResult = "Totes";

        var iStub = MockRepository.GenerateStub<IStubbable>();

        const string prop1 = "cool stub bro";
        iStub
            .Stub(x => x.DoStuff(Arg<Parameter>.Matches(y => y.Property1 == prop1)))
            .Return(expectedResult);


        var service = new ThisService(iStub);

        var result = service.DoTheStuff(new Parameter() {Property1 = prop1});

        Assert.AreEqual(expectedResult, result);
    }
公共类参数
{
公共字符串属性1{get;set;}
}
公共接口是可质疑的
{
字符串DoStuff(参数param);
}
公共服务
{
私人IStubbable _stubable;
公共服务(IsTubble stubable)
{
_短梗=短梗;
}
公共字符串DoTheStuff(参数param)
{
返回_stubbable.DoStuff(参数);
}
}
[测试]
公共void teststubing()
{
常量字符串expectedResult=“Totes”;
var iStub=MockRepository.GenerateStub();
const string prop1=“cool stub bro”;
伊斯图布
.Stub(x=>x.DoStuff(Arg.Matches(y=>y.Property1==prop1)))
.返回(预期结果);
var服务=新的此服务(iStub);
var result=service.DoTheStuff(新参数(){Property1=prop1});
Assert.AreEqual(预期结果、结果);
}

这篇文章提供了实现这一点的另一种方法。

将存根更改为:

        iStub.Stub(x => x.DoStuff(new Parameter()))
            .Constraints(new PredicateConstraint<Parameter>(y => y.Property1 == prop1 ))
            .Return(expectedResult);
issub.Stub(x=>x.DoStuff(新参数()))
.Constraints(新谓词约束(y=>y.Property1==prop1))
.返回(预期结果);