如何在C#和Rhinomocks的模拟器上设置属性?

时间:2011-06-04 07:56:10

标签: c# unit-testing rhino-mocks

我在设置Rhinomocks中的属性值时遇到问题。我需要在测试方法之外设置属性的初始值,然后有条件地在测试中的方法中设置它的值。一些代码:

public interface IResponse
{
    string ResponseText { get; set; }
}

public void ProcessResponse(IResponse response)
{
    if(response.ResponseText == "Unset")
    {
        response.ResponseText = someService.GetResponse();//someService here is irrelvant to the question
    }
}

[TestMethod]
public void ResponseValueIsSetWhenConditionIsTrueTest()
{
    var mock = Mock<IResponse>.GenerateMock();
    mock.Stub(x => x.ResponseText).Returns("Unset");

    Processor.ProcessResponse(mock);

    Assert.AreEqual("Responseval", mock.ResponseText); //Fails because the method doesn't set the value of the property.
}

我需要mock的属性将初始值放入测试的Act部分,并允许测试中的方法更改该值,以便稍后我可以断言。但是mock.ResponseText始终设置为“Unset”,并且该方法永远不会更改其值 - 这里发生了什么?

2 个答案:

答案 0 :(得分:12)

你试过PropertyBehavior吗?例如:

mock.Stub(x => x.ResponseText).PropertyBehavior();

然后在你的测试中:

mock.ResponseText = "Unset";
Processor.ProcessResponse(mock);
Assert.AreEqual("Responseval", mock.ResponseText);

答案 1 :(得分:3)

首先,Rhino.Mocks中模拟存根之间的行为存在差异。其次,我不确定您使用的是哪种版本的Rhino.Mocks,但使用最新版本和 AAA语法,这当然有效:

public interface IResponse
{
    string ResponseText { get; set; }
}

...

    [Test]
    public void Test()
    {
        IResponse response = MockRepository.GenerateStub<IResponse>();

        response.ResponseText = "value1";
        Assert.AreEqual("value1", response.ResponseText);

        response.ResponseText = "value2";
        Assert.AreEqual("value2", response.ResponseText);
    }