单元测试仅使用setter属性,仅通过向属性添加getter而失败

时间:2011-11-22 13:24:36

标签: c# unit-testing nunit rhino-mocks

我最近围绕一个只有一个setter的属性创建了一个测试,今天我修改了该属性以在接口中包含一个getter,然后测试用例失败了。

我已经创建了一个简单的工作和失败的例子,如下所示。 我不确定它是我的无知还是Rhino.Mocks或NUnit中出现此行为的错误。

我愿意接受任何意见。

我在Windows 7 64bit上使用Visual Studio 2010。 我正在使用Rhino.Mocks 3.6(尝试2.6 build 21以及相同的结果) 我使用的是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)));
        }
    }
}

失败报告消息。

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 

2 个答案:

答案 0 :(得分:1)

Stub对象具有读/写属性的默认get / set属性行为。您可以使用DynamicMock显式处理属性。

答案 1 :(得分:1)

更改

MockRepository.GenerateStub<ITest>();

MockRepository.GenerateMock<ITest>();

通常,如果要对具有期望的行为进行断言,则需要模拟,而不是存根。存根将创建自己的getter和setter,无法验证行为。

您还可以将AssertWasCalled简化为:

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