user5447154
user5447154

Reputation:

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

enter image description here any help is welcome.

Upvotes: 0

Views: 1477

Answers (1)

David Osborne
David Osborne

Reputation: 6801

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

Upvotes: 3

Related Questions