【问题标题】:Unit Test passes with setter only property, failing by just adding getter to the property单元测试仅通过 setter 属性,仅通过将 getter 添加到属性而失败
【发布时间】:2011-11-22 13:24:36
【问题描述】:

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

我创建了一个关于它的工作和失败的简化示例,如下所示。 我不确定是我的无知还是 Rhino.Mocks 或 NUnit 中呈现这种行为的错误。

我会欣赏任何意见。

我在 Windows 7 64 位上使用 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 

【问题讨论】:

  • 好吧,这很快,我完全忘记了 Mock verse Stub 的行为。有点困惑,它现在完全可以与 Mock 一起工作,而且只有一个二传手。谢谢。
  • 这些不是你真正的测试吗?您无需测试简单的 setter/getter 工作。
  • 这些是展示行为的简化示例,实际测试用例的类型具有需要检查的多个字段。

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


【解决方案1】:

改变

MockRepository.GenerateStub<ITest>();

MockRepository.GenerateMock<ITest>();

一般来说,如果你想断言一个带有期望的行为,你需要一个模拟,而不是一个存根。存根会创建自己的无法验证行为的 getter 和 setter。

您还可以将AssertWasCalled 简化为:

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

【讨论】:

  • 我意识到我可以简化这个案例的测试用例,因为我简化了属性的类型。但是,简化 AssertWasCalled 的示例不适用于 SetOnlyProperty 情况。
【解决方案2】:

Stub 对象具有读取/写入属性的默认获取/设置属性行为。您可以改用 DynamicMock 来显式处理属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 2023-04-02
    相关资源
    最近更新 更多