Search code examples
c#rhino-mocks

How to throw an exception when setting property in Rhino Mocks


My stub should throw an exception when its property (a double) is set (to any value). How can I accomplish this using Rhino Mocks 3.5?

I tried this:

        var myMock = MockRepository.GenerateStub<MyInterface>();
        myMock.Stub(x => x.MyProperty).Throw(new Exception());

But that gives me:

System.InvalidOperationException : You are trying to set an expectation on a property that was defined to use PropertyBehavior.
Instead of writing code such as this: mockObject.Stub(x => x.SomeProperty).Return(42);
You can use the property directly to achieve the same result: mockObject.SomeProperty = 42;

But in this case I am not talking about setting and getting a simple value, it should throw.


Solution

  • You must replace with MockRepository.GenerateMock,

    This version has problem with GenerateStub,

    var myMock = MockRepository.GenerateMock<MyInterface>();
    myMock.Stub(x => x.MyProperty).Throw(new Exception());