1

是否有可能在 rhino mock 中做某种形式的期望 NEW。

例子:

public void ToBeTested()
{
     ClassForExmaple classForExample = new ClassForExample();

     //Other logic.....
}

所以我希望我的单元测试调用 ToBeTested(),但是当调用新的 ClassForExample 时,我希望它返回一个模拟版本。

4

2 回答 2

1

我没有使用过 Rhino mock,我不确定这是否是 RhinoMock 支持的东西,但是对象创建的控制嵌入在方法中的事实违反了 DI/IOC 的原则,因此更难测试.. 理想情况下,该类应该通过包含类的构造函数或方法本身注入到方法中。

因此

class A
{
    IClassForExample _classForExample;
    public A(IClassForExample classForExample)
    {
      _classForExample=classForExample;
    }
    public void ToBeTested()
    {
         var classForExample = _classForExample;

         //Other logic.....
    }
}

RhinoSupport 是否扩展了非抽象/接口类 - 我不确定这个问题,但我确信它可以模拟接口。

于 2012-06-21T09:21:41.660 回答
0

不,这是不可能的,出于同样的原因你不能期待static事情:它不是在实例上调用的。

如果您想对在测试代码中构建的对象使用模拟,您应该有这样的东西:

internal virtual ClassForExample NewClassForExempe()
{
    return new ClassForExample();
}

然后在你的测试中模拟这个方法。

注意:假设您在类的InternalsVisibleToAttribute中声明了 rhino 模拟,我将方法放在内部。否则,您将不得不将其公开。

于 2012-06-21T09:21:16.090 回答