Rhino Mocks - 设置属性时引发事件

发布于 2024-11-06 06:24:52 字数 484 浏览 0 评论 0原文

每当使用 Rhino Mocks 设置某个属性时,我想在存根对象上引发一个事件。例如

public interface IFoo
{
   int CurrentValue { get; set; }
   event EventHandler CurrentValueChanged;
}

设置 CurrentValue 将引发 CurrentValueChanged 事件

我已经尝试过 myStub.Expect(x => x.CurrentValue).WhenCalled(y => myStub.Raise ... 不起作用,因为该属性是可设置的,并且它说我正在对已定义为使用 PropertyBehaviour 的属性设置期望。此外,我也知道这是一种滥用。我对此不太满意的 WhenCalled

实现此目标的正确方法是什么?

I want to raise an event on a stub object whenever a certain property is set using Rhino Mocks. E.g.

public interface IFoo
{
   int CurrentValue { get; set; }
   event EventHandler CurrentValueChanged;
}

Setting CurrentValue will raise the CurrentValueChanged event

I have tried myStub.Expect(x => x.CurrentValue).WhenCalled(y => myStub.Raise... which doesn't work because the property is settable and it says I'm setting expectations on a property which is already defined to use PropertyBehaviour. Also I am aware that this is an abuse of WhenCalled which I'm none too happy about.

What the correct way of achieving this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

皇甫轩 2024-11-13 06:24:52

您很可能创建了一个存根,而不是一个模拟。唯一的区别是存根默认具有属性行为。

所以完整的实现如下:

IFoo mock = MockRepository.GenerateMock<IFoo>();
// variable for self-made property behavior
int currentValue;

// setting the value: 
mock
  .Stub(x => CurrentValue = Arg<int>.Is.Anything)
  .WhenCalled(call =>
    { 
      currentValue = (int)call.Arguments[0];
      myStub.Raise(/* ...*/);
    })

// getting value from the mock
mock
  .Stub(x => CurrentValue)
  // Return doesn't work, because you need to specify the value at runtime
  // it is still used to make Rhinos validation happy
  .Return(0)
  .WhenCalled(call => call.ReturnValue = currentValue);

You most probably created a stub, not a mock. The only difference is that the stub has property behavior by default.

So the full implementation is something like the following:

IFoo mock = MockRepository.GenerateMock<IFoo>();
// variable for self-made property behavior
int currentValue;

// setting the value: 
mock
  .Stub(x => CurrentValue = Arg<int>.Is.Anything)
  .WhenCalled(call =>
    { 
      currentValue = (int)call.Arguments[0];
      myStub.Raise(/* ...*/);
    })

// getting value from the mock
mock
  .Stub(x => CurrentValue)
  // Return doesn't work, because you need to specify the value at runtime
  // it is still used to make Rhinos validation happy
  .Return(0)
  .WhenCalled(call => call.ReturnValue = currentValue);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文