Search code examples
c#unit-testingmockingrhino-mocks

Rhino Mocks, how can I perform an action after setting a Stub property


I have a simple requirement, but I seem to be struggling.

I have created a stub that mocks an interface that includes a Property :

public interface IMockIRuleRuningViewModel : IRuleRunningViewModel
{
    int Id { get; set; }
}

And the mock is :

var mock = MockRepository.GenerateStub<IMockIRuleRuningViewModel>();

Now I want to mock an action that I would have put in a setter for this Property, and here is my attempt :

mock.Stub(x => x.Id).WhenCalled(
    o =>
        {
            var engine = new RulesEngine(mock);
            mock.ProcessRuleEngineResults(engine.RunRule("Id"));
        });

But I keep getting this Exception :

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;


Solution

  • If you want to verify the behavior of the SUT (system under test), you should use a mock with the appropriate expectation, and verify that. If you want just to pass a value that may need to act in a certain way, but isn't the focus of this test, you will use a stub (stub will not cause a test to fail).

    I assume that you are testing RulesEngine in this test (because it is only real object I see). Here is a sample test, which verifies behavior of engine, when "Id" rule was executed:

    // Arrange
    var model = MockRepository.GenerateMock<IMockIRuleRuningViewModel>();
    model.Expect(m => m.ProcessEngineResults(42));
    RulesEngine engine = new RulesEngine(model);
    
    // Act
    engine.RunRule("Id");
    
    // Assert
    model.VerifyAllExpectations();