我有一个简单的需求,但我似乎很挣扎。
我创建了一个 stub
来模拟一个包含 Property
的 interface
:
public interface IMockIRuleRuningViewModel : IRuleRunningViewModel
{
int Id { get; set; }
}
mock
是:
var mock = MockRepository.GenerateStub<IMockIRuleRuningViewModel>();
现在我想模拟
一个我会为这个Property
放入setter的 Action ,这是我的尝试:
mock.Stub(x => x.Id).WhenCalled(
o =>
{
var engine = new RulesEngine(mock);
mock.ProcessRuleEngineResults(engine.RunRule("Id"));
});
但我不断收到此Exception
:
You are trying to set an expectation on a property that was defined to use PropertyBehavior. Instead of writing code such as this: mockObject.Stub(x => x.SomeProperty).Return(42); You can use the property directly to achieve the same result: mockObject.SomeProperty = 42;
最佳答案
以下对我有用:
HttpResponseBase response = MockRepository.GenerateMock<HttpResponseBase>();
// stub the getter
response.Stub(r => r.StatusCode).Return((int)HttpStatusCode.OK);
// Stub the setter
response.Stub(r => r.StatusCode = Arg<int>.Is.Anything).WhenCalled( o =>
{
Console.WriteLine("called");
});
因为我实际上想做的是模拟您可以获得但不能设置状态代码的情况(因为 header 已经发送),所以我不执行 WhenCalled()
,我这样做:
response.Stub(r => r.StatusCode = Arg<int>.Is.Anything)
.Throw(new HttpException("Server cannot set status after HTTP headers have been sent"));
您必须使用 MockRepository.GenerateMock
而不是 MockRepository.GenerateStub
。我不知道为什么。
关于c# - Rhino Mocks,设置 stub 属性后如何执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10687715/