c# - Rhino Mocks,设置 stub 属性后如何执行操作

标签 c# unit-testing mocking rhino-mocks

我有一个简单的需求,但我似乎很挣扎。

我创建了一个 stub 来模拟一个包含 Propertyinterface :

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/

相关文章:

c# - 在 MVC 5 中填充 DropDownList

c# - 禁用 winforms 设计器中的属性设置

c# - 从 UDP 连接接收结构化数据

c# - 为什么 C# 不像 C 那样支持局部静态变量?

android - 尝试使用 Robolectric 读取 Assets 时出现 FileNotFoundException

c# - 模拟一个方法,该方法返回对另一个对象的方法调用

c# - 有没有办法从 SQL 表或查询生成对象初始值设定项?

c# - 如何在 EF 中模拟和单元测试存储过程

ruby - 使用 RSpec 模拟 TCPSocket

unit-testing - 单元测试 - 数据库和固定装置