用Rhino模拟抽象类的默认行为 [英] Mock abstract class default behaviour with Rhino
问题描述
我对模拟还很陌生,所以这可能只是我尚未了解的东西,但我在任何地方都找不到很好的例子.
I'm pretty new to mocking so this might be something I'm just not picking up on yet, but I can't find a good example anywhere.
我试图断言默认情况下,任何从我的抽象类继承的类都将在构造函数中实例化一个集合.这是抽象类:
I'm trying to assert that by default, any class that inherits from my abstract class will instantiate a collection in the constructor. Here's the abstract class:
public abstract class DataCollectionWorkflow : SequentialWorkflowActivity
{
private readonly DataSet _output = new DataSet();
private List<DataCollectionParameter> _params = null;
public DataCollectionWorkflow()
{
_params = new List<DataCollectionParameter>();
}
public virtual IList<DataCollectionParameter> Parameters
{
get { return _params; }
set { _params = (List<DataCollectionParameter>)value; }
}
}
我如何用Rhino嘲笑它?如果我执行GenerateMock<DataCollectionWorkflow>
(或存根),则构造函数将运行,并且模拟的私有字段"_params
"被初始化,但是模拟的"Parameters
"属性只是空.
How do I mock this with Rhino? If I do a GenerateMock<DataCollectionWorkflow>
(or a stub), the constructor runs and the mock's private field "_params
" gets initialized, but the mock's "Parameters
" property is simply null.
显然,生成的模拟子类将覆盖属性实现.有什么方法可以排除重新实现的Parameters属性吗?
Obviously the generated mock subclass is overriding the property implementation. Is there some way of excluding the Parameters property from being re-implemented?
谢谢.
推荐答案
好的,我知道了.让我不禁为Rhino的错综复杂而伤亡.这种事情使我想转向一个更简单的框架,也许我会签下MoQ.
Okay, I figured it out. Chalk me up as another casualty to the intricacies of Rhino. This kind of thing makes me want to move to a simpler framework, maybe I'll check out MoQ.
所以答案是使用PartialMocks.我曾短暂地尝试过生成部分模拟,但是当我在其上运行调试器时,我注意到这些属性甚至都不为null,它们抛出了怪异的异常,因此我看上去并不更深入.我使用的是简写AAA类型的语法.
So the answer is using PartialMocks. I had briefly toyed with generating a partial mock, but when I ran the debugger over it I noticed that the properties weren't even null, they were throwing weird exceptions, so I didn't look much deeper. I was using the short form AAA type of syntax.
如果我只是简单地将模拟置于播放模式,结果就可以正常运行-该属性按原样使用(因为它们应该与部分模拟一起使用).
Turns out if I simply put the mock into playback mode, the test works - the properties are used as is (as they should be with a partial mock).
所以这是答案:
[Test]
public void ShouldCreateParameterListInConstructor()
{
var mockRepository = new MockRepository();
var mock = mockRepository.PartialMock<DataCollectionWorkflow>();
using ( mockRepository.Record() )
{
}
using (mockRepository.Playback())
{
Assert.That(mock.Parameters, Is.Not.Null, "DataCollectionWorkflow base class didn't create new param collection");
}
}
我意识到这是一个有状态的测试,但是实际上,这是某些涉及所讨论属性的行为测试的简单前奏,因此我希望将此情况作为前提条件.希望它能对某人有所帮助.
I realize that this is a stateful test but it's actually a simpler prelude to some behavioural testing that involves the property in question, so I wanted this case as prerequisite. Hope it helps someone.
这篇关于用Rhino模拟抽象类的默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!