本文介绍了我可以让 Rhino Mocks GenerateStub 或 GenerateMock 每次都返回一个新类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含所有不同具体类型的对象的 IList,因此:

I want to create an IList of objects that are all different concrete types, so:

var tasks = new List<ITask>();
foreach (string taskName in taskNames)
{
    var task = MockRepository.GenerateStub<ITask>();
    task.Stub(t => t.Name).Return(taskName);
    tasks.Add(task);
}
return tasks;

问题是每个存根对象都是相同的具体类型.通常这很好,但我有一个案例,我想测试每个是不同类型的.在这种情况下,我可以以某种方式配置 Rhino Mocks 来执行此操作吗?

The problem is that each stub object is all the same concrete type. Normally this is fine, but I have a case where I want to test each one being a different type. Can I somehow configure Rhino Mocks to do this, in this case?

编辑:

you-must-be-doing-wrong-crew"今天生效.由于你们似乎都认为我需要先证明我的用例,然后才能回答我的问题,这就是我正在做的:

The "you-must-be-doing-it-wrong-crew" are out in force today. Since you all seem to think I need to justify my use-case before you can take a stab at answering my question, here's what I'm doing:

  • ITask 在我的域模型中,所以它是我的业务层的一部分.
  • 我在将 ITask 作为参数的更高级别(表示)层中有逻辑.
  • 表示层逻辑通常会在 ITask 上执行默认的 Strategy,但在某些特殊情况下,我们需要使用不同的 Strategy,而要使用的 Strategy 完全取决于 ITask 对象的具体类型.
  • 常规策略模式在这里不起作用,因为这需要我的具体 ITask 对象知道它们上面的层.
  • 装饰者仍然必须知道他们装饰的对象的具体类型,并且必须在构建时(这种情况下错误的层)或在使用时应用,但这给我带来了同样的问题 - 应用一个基于具体类型的装饰器.
  • 我决定在 WPF 中使用 DataTemplates(和 DataType 属性)使用的相同模式.也就是说,给定一个来自较低层的对象,看看是否有人注册了一个策略来处理该类型,如果是,则使用它.否则,请使用默认策略.

所以,我希望你能明白我为什么需要测试逻辑.到目前为止,我不得不编写自己的 Stub 工厂,该工厂从有限的具体 ITask 类型池中生成.它有效,但我宁愿让 Rhino Mocks 为我做这件事.

So, I hope you can see why I need the test logic. So far I've had to write my own Stub factory that generates from a limited pool of concrete ITask types. It works, but I'd rather let Rhino Mocks do it for me.

推荐答案

您可以添加 ITask.Type 属性.

对接口背后的类型感兴趣的代码应该使用这个属性而不是调用GetType().在您的测试中,控制 Type 属性为任何给定的 ITask 存根返回的内容变得微不足道.

The code which is interested in the type behind the interface should then use this property instead of calling GetType(). In your tests, it then becomes trivial to take control of what the Type property returns for any given ITask stub.

这篇关于我可以让 Rhino Mocks GenerateStub 或 GenerateMock 每次都返回一个新类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:43