How to set a property on a mock in C# and Rhinomocks?
I am having problems setting the value of a property in Rhinomocks. I need to set the initial value of the property outside the method under test and then set its value inside the method under test conditionally. Some code:
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 ResponseValueIsSe开发者_如何学PythontWhenConditionIsTrueTest()
{
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.
}
I need the mock's property to have an initial value going into the Act part of the test, and allow the method under test to change that value so I can assert on it later. However mock.ResponseText
is always set to "Unset", and the method never changes its value - what is going on here?
Have you tried PropertyBehavior
? For example:
mock.Stub(x => x.ResponseText).PropertyBehavior();
Then in your test:
mock.ResponseText = "Unset";
Processor.ProcessResponse(mock);
Assert.AreEqual("Responseval", mock.ResponseText);
First of all, there's a difference in behavior between mocks and stubs in Rhino.Mocks. Secondly, I'm not sure what version of Rhino.Mocks you are using, but using the latest one and AAA syntax, this certainly works:
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);
}
精彩评论