Rhino Mocks - Set a property if a method is called

2019-01-24 09:03发布

问题:

Is there a way with Rhino Mocks to set a property of a Stub if a method is called.

Something like this: (Fake Code in bold)

callMonitor.Expect(x=>x.HangUp()).SetProperty(callMonitor.InACall = false);

The HangUp method returns void and I can't really change that. But I want my stub to know that the call was hung up when HangUp is called.

回答1:

You can use the "WhenCalled" method to run your own code when a stub is called; pretty sure it should work with Mocks, too. According to the documentation, WhenCalled is a replacement/upgrade for Callback.

callMonitor.Expect(x => x.HangUp())
.WhenCalled(invocation => callMonitor.InCall = false);

Some info at the end of this post: http://grahamnash.blogspot.com/2008/10/rhino-mocks-35.html



回答2:

Yes, you can use the Callback method:

 callMonitor.Expect(x => x.HangUp()).Callback(() => callMonitor.InCall = false);


回答3:

There might be some conditions under which you would need to do this, but generally I would expect that you would simply instrument your mock/stub so that it returns the proper values in response to your code. The only exceptions to this that I can think of are partial mocks where you are testing one part of a class and want to mock the other parts.

Setting a mock on a property is pretty easy.

callMonitor.Expect( x => x.HangUp() );
callMonitor.Expect( x => x.InACall ).Return( false );

If callMonitor is a stub, then you can set the property directly.

callMonitor.Stub( x => x.HangUp() );
callMonitor.InACall = false;


回答4:

I'm no RhinoMocks expert, but I believe this should work.

SetupResult.For(callMonitor.InACall).Return(false);