如何嘲笑静态单身? [英] How to Mock a Static Singleton?

查看:129
本文介绍了如何嘲笑静态单身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我一直在问到一些单元测试添加到使用犀牛制品和有一些问题类数。

I have number of classes I've been asked to add some unit tests to with Rhino Mocks and having some issues.

首先,我知道RhinoMocks的没有按' ŧ允许静态成员的嘲弄。 。我在找我有什么选择(除了使用TypeMock)

First off, I know RhinoMocks doesn't allow for the mocking of Static members. I'm looking for what options I have (besides using TypeMock).

类我有一个例子是类似如下:

An example of the class I have is similar to the below:

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.
}



所以,当我拨打上面的​​类,它看起来是这样的......

So when I call the above class, it looks something like this...

Example1.Instance.SomeObject.GoDownARabbitHole();



有没有办法对我来说,模拟出了 SomeObject.GoDownARabbitHole() 在这种情况下或模拟出来的实例?

Is there a way for me to mock out the SomeObject.GoDownARabbitHole() in this situation or mock out the Instance?

推荐答案

单身人士在与可测试性的赔率,因为他们是如此难以改变。你会好得多使用的依赖关系注入以注入一个ISomeInterface实例到你的消费类:

Singletons are at odds with Testability because they are so hard to change. You would be much better off using Dependency Injection to inject an ISomeInterface instance into your consuming classes:

public class MyClass
{
    private readonly ISomeInterface dependency;

    public MyClass(ISomeInterface dependency)
    {
        if(dependency == null)
        {
            throw new ArgumentNullException("dependency");
        }

        this.dependency = dependency;
    }

    // use this.dependency in other members
}

注意如何与只读关键字担保卫队克劳斯在一起的ISomeInterface实例将始终可用。

Notice how the Guard Claus together with the readonly keyword guarantees that the ISomeInterface instance will always be available.

这将允许您使用犀牛制品或其他动态模拟库注入ISomeInterface的测试双打进入消费类。

This will allow you to use Rhino Mocks or another dynamic mock library to inject Test Doubles of ISomeInterface into the consuming classes.

这篇关于如何嘲笑静态单身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆