[英]C# How to unit test a method that calls a static method that has external dependency?
I have a method as below that uses a static method from NamaspaceManager class. 我有如下方法,该方法使用NamaspaceManager类中的静态方法。
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. 由于该函数对NamespaceManager类具有严格的依赖性,因此在单元发布过程中,它希望我提供有效的连接字符串。 Also, I don't have any control over the NamespaceManager class as it comes with NuGet package. 另外,由于NuGet包随附,我对NamespaceManager类没有任何控制权。 How do I refactor it to make it unit testable? 我如何重构它使其可测试?
I think that you should refactor your method to accept a NamespaceManager object. 我认为您应该重构您的方法以接受NamespaceManager对象。 Then you can create a NamespaceManager object in your test, add the relevant Queue to it and pass it into the method. 然后,您可以在测试中创建一个NamespaceManager对象,向其中添加相关的Queue并将其传递给方法。
If you want to keep your existing client code untouched then you could check for null and run the existing code, eg 如果要保持现有客户端代码不变,则可以检查是否为空并运行现有代码,例如
public long GetCount(string name, NamespaceManager namespaceManager = null)
{
if(namespaceManager == null)
{
namespaceManager = NamespaceManager.CreateFromConnectionString(this.queueConfig.ConnectionString);
}
return namespaceManager.GetQueue(name).MessageCountDetails.ActiveMessageCount;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.