代码之家  ›  专栏  ›  技术社区  ›  Anee

为什么要从Expect()语句调用方法?

  •  1
  • Anee  · 技术社区  · 11 年前

    我试图对Mocked对象设置一个期望值,以确定该方法是否按预期调用。

    我使用以下代码来实现它。

    //// Create a mocked object(arrange)
    A controller = MockRepository.GenerateMock<A>();
    someObject.Stub(x => x.Resolve(typeof(A))).Return(controller);
    
    //// Act i.e. call the target function where the controller is created
    this._target.InvokePrivateMethod("OnTargetUpdated", false, this, eventArgs);
    
    //// Assert
    controller.AssertWasCalled(x => x.UpdateTarget(targetInfo2), o => o.Repeat.Once());
    

    然而,当我试图断言是否调用了“UpdateTarget()”时,流会进入方法的代码中。我只想检查“如果方法被调用了”,而不是“调用方法”。

    1 回复  |  直到 11 年前
        1
  •  1
  •   Community CDub    7 年前

    As方法 UpdateTarget() 是非虚拟的,那么Rhino Mock无法拦截对它的调用。

    这就是为什么实际方法被执行的原因。
    参见详细信息,例如 this question .

    为了让你的测试发挥作用,你需要使模拟方法成为虚拟的。如果您在这里使用接口而不是类,那就更好了。