如何在.net中存根通过反射调用的方法

本文关键字:反射 调用 方法 存根 net | 更新日期: 2023-09-27 18:16:10

我有一个基类,看起来像这样:

public Base<TReceiver, TRequest, TResponse>
    where TReceiver : class
    where TRequest : class, new()
    where TResponse : class, new()
{    
    private readonly TReceiver _receiver;
    public TRequest Request { get; set; }
    public TResponse Response { get; set; }
    protected Base(TReceiver receiver)
    {
        _receiver = receiver;
    }
    public void CallReceiver()
    {
        var receiverType = _receiver.GetType();
        var executeMethod = receiverType.GetMethod(ExecuteMethodName);
        Response = (TResponse) executeMethod.Invoke(_receiver, new object[] {Request});
    }
    protected abstract string ExecuteMethodName { get; }
}

派生类是这样的:

public class Derived : BaseCommand<IReceiver, DerivedRequest, DerivedResponse>
{
    public Derived (IReceiver receiver)
        : base(receiver)
    {
    }
    protected override string ExecuteMethodName
    {
        get { return "Execute"; }
    }
}

这是IReceiver接口:

public interface IReceiver
{
   DerivedResponse Execute(DerivedRequest request);
}

是否有可能在IReceiver实现中存根执行方法?

提前感谢!

如何在.net中存根通过反射调用的方法

我发现了一个错误)以下代码是正确的:

public void CallReceiver()
{
    var receiverType = typeof(TReceiver);
    var executeMethod = receiverType.GetMethod(ExecuteMethodName);
    Response = (TResponse) executeMethod.Invoke(_receiver, new object[] {Request});
}

然后我可以这样写我的接收器:

var receiverStub = MockRepository.GenerateStub<IReceiver>();
receiverStub.Stub(x => x.Execute(new DerivedRequest())).IgnoreArguments().Return(new DerivedResponse());