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

Mal*_*ker 0 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.
}
Run Code Online (Sandbox Code Playgroud)

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

Cha*_*tay 13

你试过PropertyBehavior吗?例如:

mock.Stub(x => x.ResponseText).PropertyBehavior();
Run Code Online (Sandbox Code Playgroud)

然后在你的测试中:

mock.ResponseText = "Unset";
Processor.ProcessResponse(mock);
Assert.AreEqual("Responseval", mock.ResponseText);
Run Code Online (Sandbox Code Playgroud)