【问题标题】:Reflect over decorator to assert internal mock called反射装饰器以断言调用的内部模拟
【发布时间】:2021-11-06 08:37:28
【问题描述】:

我有一个接口,IFoo,有一些方法。我还有一个装饰任何 IFoo 的 IFoo 实现,例如:

class FooDecroator : IFoo {
  FooDecorator(IFoo decoratedFoo) {
    ...
  }

  public void SomeFooMethod() {
    decoraterdFoo.SomeMethod();
  }
}

我想使用 FakeItEasy 来模拟构造函数 arg,这样我就可以断言一切都被正确委派了。我可以手动写出每个调用,但我有一些逻辑,其中某些方法没有被委托。

我知道我可以使用反射遍历 FooDecorator,获取公共方法,获取每个方法的参数,并使用反射调用该方法。

我不确定的是如何断言模拟方法是使用反射(或其他方式)使用相同的参数调用的。我试图避免为每个方法调用编写代码。

感谢任何想法。

【问题讨论】:

    标签: c# fakeiteasy


    【解决方案1】:

    最好的办法可能是使用CallTo 变体来指定对对象的任何调用:Specifying a call to any method or property(页面标题提到指定对configure的调用,但A.CallTo 是也用于验证)。有一个 Where 重载,它接受一个测试 IFakeObjectCall 的谓词,它可以访问被调用的方法和传递的参数:

    A.CallTo(wrappedFake)
        .Where(call => CallMatchesMethodAndArguments(call, method, outerArguments)
        .MustHaveHappened();
    
    …
    
    bool CallMatchesMethodAndArguments(
        IFakeObjectCall call,
        MethodInfo method,
        object[] outerArguments)
    {
       // check call.Method matches method
       // check each of call.Arguments matches outerArguments
    }
    

    【讨论】:

    • 我在文档中错过了这个,谢谢。我明天会检查它,如果它有效,我会告诉你。
    猜你喜欢
    • 2016-01-06
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多