Robin Luiten
Robin Luiten

Reputation: 5328

Unit Test passes with setter only property, failing by just adding getter to the property

I created a test recently around a property with only a setter, today I modified the property to include a getter in the interface and the test case then failed.

I have created a boiled down example of it working and failing which is below. I am not sure if its my ignorance or maybe a bug in Rhino.Mocks or NUnit that is presenting this behaviour.

I would appreaciate any input.

I am using Visual Studio 2010 on Windows 7 64bit. I am using Rhino.Mocks 3.6 (tried 2.6 build 21 as well for same results) I am using NUnit-2.5.10.11092

using NUnit.Framework;
using Rhino.Mocks;
using Rhino.Mocks.Constraints;

namespace PropertyTestFailure
{
    public interface ITest
    {
        int SetOnlyProperty { set; }
        int SetGetProperty { get;  set; }
    }

    /// <summary>
    /// The property with getter fails.
    /// It appears purely adding the getter that breaks things.
    /// </summary>
    [TestFixture]
    public class TestCase
    {
        [Test]
        public void SetOnlyPropertyWorks()
        {
            var mockTest = MockRepository.GenerateStub<ITest>();

            mockTest.SetOnlyProperty = 23;

            mockTest.AssertWasCalled(x => x.SetOnlyProperty
                = Arg<int>.Matches(new PredicateConstraint<int>(y => y == 23)));
        }

        [Test]
        public void SetGetPropertyFails()
        {
            var mockTest = MockRepository.GenerateStub<ITest>();

            mockTest.SetGetProperty = 24;

            mockTest.AssertWasCalled(x => x.SetGetProperty
                = Arg<int>.Matches(new PredicateConstraint<int>(y => y == 24)));
        }
    }
}

The failure report message.

SetGetPropertyFails : FailedRhino.Mocks.Exceptions.ExpectationViolationException : ITest.set_SetGetProperty(Predicate (TestCase.<SetGetPropertyFails>b__5(obj);)); Expected #1, Actual #0.
at Rhino.Mocks.RhinoMocksExtensions.AssertWasCalled(T mock, Action`1 action, Action`1 setupConstraints)
at PropertyTestFailure.TestCase.SetGetPropertyFails() in TestCase.cs: line 40 

Upvotes: 1

Views: 1041

Answers (2)

vcsjones
vcsjones

Reputation: 141638

Change

MockRepository.GenerateStub<ITest>();

to

MockRepository.GenerateMock<ITest>();

Generally if you want to assert on a behavior with an expectation, you will want a mock, not a stub. A stub will create its own getters and setters that can't verify behavior.

You can also simplify your AssertWasCalled to:

mockTest.AssertWasCalled(x => x.SetGetProperty = 24);

Upvotes: 1

Eric Nicholson
Eric Nicholson

Reputation: 4123

A Stub object has default get/set property behavior for read/write properties. You can use a DynamicMock instead to handle properties explicitly.

Upvotes: 1

Related Questions