1

I have a method as below that uses a static method from NamaspaceManager class.

public long GetCount(string name)
{
    var namespaceManager = NamespaceManager.CreateFromConnectionString(this.queueConfig.ConnectionString);
    return namespaceManager.GetQueue(name).MessageCountDetails.ActiveMessageCount;
}

Since the function has hard dependency on NamespaceManager class, during unit tetsing, it expects me to provide a valid connection string. Also, I don't have any control over the NamespaceManager class as it comes with NuGet package. How do I refactor it to make it unit testable?

vrcks
  • 419
  • 1
  • 5
  • 23

1 Answers1

1

I think that you should refactor your method to accept a NamespaceManager object. Then you can create a NamespaceManager object in your test, add the relevant Queue to it and pass it into the method.

If you want to keep your existing client code untouched then you could check for null and run the existing code, e.g.

public long GetCount(string name, NamespaceManager namespaceManager = null)
{
    if(namespaceManager == null)
    {
        namespaceManager = NamespaceManager.CreateFromConnectionString(this.queueConfig.ConnectionString);
    }
    return namespaceManager.GetQueue(name).MessageCountDetails.ActiveMessageCount;
}
DeanOC
  • 7,142
  • 6
  • 42
  • 56
  • But NamespaceManager expects a valid connection string to a queue. I want to wrap NamespaceManager but don't have the necessary control. I will have to maintain a queue during every unit test run which is not feasible. – vrcks Jul 10 '17 at 06:31
  • 1
    Ahh, I see your problem. Then I think this answer is your best bet. https://stackoverflow.com/a/40723011/845655 – DeanOC Jul 10 '17 at 06:39
  • vrcks, did the solution work for you? I'm having a similar problem as yours. – Josh Monreal Oct 06 '20 at 15:53