简体   繁体   English

如何使用NSubstitute模拟单例类?

[英]How can I mock a singleton class with NSubstitute?

I have a Singleton class, something like this : 我有一个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)
            {
            }
      }

How can I mock this class with NSubstitute ? 如何使用NSubstitute模拟此类?

in other hand : I want something like this 另一方面:我想要这样的东西

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

this is a quick Watch when I debug this code 当我调试此代码时,这是一个快速观察

在此处输入图片说明 any help is welcome. 欢迎任何帮助。

I can't remember the implementation of the Ambient Context pattern, I don't have the book to hand. 我不记得Ambient Context模式的实现,我没有书。 However, it would look something like this: 但是,它看起来像这样:

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)
    {
    }
}

Then your test can do this: 然后您的测试可以做到这一点:

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

Your functional code can do this, working with the default instance, or the fake one: 您的功能代码可以使用默认实例或伪实例来执行此操作:

XConnector.Current.GetData(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM