Search code examples
c#rhino-mocks

Reset Rhino Mocks AssertWasNotCalled


I have a class like this:

public class MyClass
{
    private MyStruct _someProperty;
    public MyStruct SomeProperty
    {
        set
        {
            if(StructureChanged(_someProperty, value))
            {
                _someProperty = value;
                OnSomePropertyChanged();
            }
        }
    }

    private bool StructureChanged(MyStruct oldValue, MyStruct newValue)
    {
        // Check if any property of newValue is different from oldValue
        // This is a check for semantic equality, not referential equality
    }

    internal protected virtual OnSomePropertyChanged()
    {
        // ...
    }
}

And a test like this:

// Arrange
_myClass = MockRepository.GeneratePartialMock<MyClass>();
_myClass.SomeProperty = new MyStruct();

// Act
_myClass.SomeProperty = new MyStruct(); // This is semantically equal to the current value

// Assert
_myClass.AssertWasNotCalled(m => m.OnSomePropertyChanged());

Of course, the test fails because OnSomePropertyChanged is called when I set the property the first time. What I want is to set the property the first time, reset the AssertWasNotCalled value somehow, and then set the property again and make sure OnSomePropertyChanged is not called again. Is there any way to do this?


Solution

  • Actually, in that case this is expected that OnSomePropertyChanged() is called once. But not more and not less than once.

    The suitable assert statement then might look like:

    _myClass.AssertWasCalled(m => m.OnSomePropertyChanged(), opt => opt.Repeat.Once());
    

    PS

    Another test should be written which ensures OnSomePropertyCnahged() is triggered after SomeProperty is actually changed.

    In that case in our test it is guaranteed OnSomePropertyCnahged() is triggered when SomeProperty was changed first time.
    And expectation it is called once, but not two times, guarantees that event is not fired when that is not expected.