如何使用NSubstitute模拟单例类?

时间:2017-04-20 08:09:14

标签: c# .net unit-testing mocking nsubstitute

我有一个Singleton类,如下所示:

public class XConnector : IXConnector
        {

            private static readonly Lazy<XConnector> instance = 
                    new Lazy<XConnector>(() => new XConnector());

            public static XConnector Instance => instance.Value;

            private XConnector()
            {
            }

            public async Task<XConnector> GetData(XConnector con)
            {
            }
      }

如何用NSubstitute嘲笑这个类?

另一方面:我想要这样的东西

var target = Substitute.For<IXConnector>();

这是我调试此代码时的快速监视

enter image description here  欢迎任何帮助。

1 个答案:

答案 0 :(得分:3)

我不记得环境上下文模式的实现,我手头没有这本书。但是,它看起来像这样:

public class XConnector : IXConnector
{
    private static IXConnector _instance = new XConnector();

    private XConnector()
    {
    }

    public static IXConnector Current
    { 
       get
       {
           return _instance;
       }
       set 
       {
           // Think about thread-safety
           // Check for null?
           _instance = value;
       }
    }

    public async Task<XConnector> GetData(XConnector con)
    {
    }
}

然后你的测试可以做到这一点:

XConnector.Current = Substitute.For<IXConnector>();

您的功能代码可以使用默认实例或虚假实例执行此操作:

XConnector.Current.GetData(...);