我有很多类(class)被要求使用 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()
或模拟实例?
最佳答案
被这样的线程吓坏了,我花了很长时间才注意到,单例并不难模拟。毕竟我们为什么要使用 C#?
只需使用反射。
使用提供的示例代码,您需要确保在将静态字段设置为模拟对象之前调用静态构造函数。否则它可能会覆盖您的模拟对象。在设置测试之前,只需在单例上调用任何没有效果的东西。
ISomeInterface unused = Singleton.Instance();
System.Reflection.FieldInfo instance = typeof(Example1).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
Mock<ISomeInterface> mockSingleton = new Mock<ISomeInterface>();
instance.SetValue(null, mockSingleton.Object);
我提供了使用 Moq 进行模拟的代码,但我猜 Rhino Mocks 非常相似。
关于c# - 如何模拟静态单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2050892/