简体   繁体   中英

How can I mock a singleton class with NSubstitute?

I have a Singleton class, something like this :

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 ?

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. 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(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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