【发布时间】:2011-01-04 06:52:37
【问题描述】:
我有一些课程被要求添加一些单元测试到 Rhino Mocks 并且遇到了一些问题。
首先,我知道 RhinoMocks 不允许模拟静态成员。我正在寻找我有哪些选择(除了使用 TypeMock)。
我有一个类的例子类似于下面:
class Example1 : ISomeInterface
{
private static ISomeInterface _instance;
private Example1()
{
// set properties via private static methods
}
static Example1()
{
_instance = new Example1();
}
public static ISomeInterface Instance()
{
get { return _instance; }
}
// Instance properties
// Other Instance Properties that represent objects that follow a similar pattern.
}
所以当我调用上面的类时,它看起来像这样......
Example1.Instance.SomeObject.GoDownARabbitHole();
有没有办法让我在这种情况下模拟出SomeObject.GoDownARabbitHole() 或模拟出实例?
【问题讨论】:
-
您是否尝试过 Moq 而不是 Rhino?我相信它可以让你模拟静态方法。请参阅superexpert.com/blog/archive/2008/06/12/… 和适配器模式部分以模拟静态方法
-
遗憾的是,改变模拟框架的决定不在我的掌控之中。我在一个庞大的代码库中,它在 Rhino 上是标准化的。至于使用适配器模式来模拟静态方法,同样可以使用 Rhino 来完成。我遇到的问题更多是通过静态方法创建单例,而不是测试静态方法本身。
-
Moq 不能模拟静态方法,而不遵循适配器模式。我应该补充一点,它比 Rhino 和其他模拟框架要好得多。
标签: c# unit-testing rhino-mocks