简体   繁体   English

C#如何对一个调用具有外部依赖关系的静态方法的方法进行单元测试?

[英]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.

相关问题 如何对依赖于本地声明的对象行为的ac#方法进行单元测试? - How to unit test a c# method that has dependency on a locally declared object's behavior? 如何对具有从外部资源获取信息的静态方法的类进行单元测试 - How to Unit Test a Class That Has a Static Method Which Gets Information From an External Resource 如何使用伪造对象的依赖关系对静态方法进行单元测试? - How to unit test a static method using a fake object for the dependency? 在 c# MSTest 单元测试中调用 Dispose() 方法是什么? - What calls Dispose() method in c# MSTest unit test? C#单元测试子方法调用参数 - c# unit test child method calls parameters 调用 Console.ReadLine() 的方法的 C# 单元测试 - C# unit test for a method which calls Console.ReadLine() 对使用moq调用静态方法的静态方法进行单元测试 - Unit test a static method that calls a static method using moq 如何在C#中对该方法进行单元测试? - How to unit test this method in c#? 无法对调用静态方法的方法进行单元测试,如何重新设计该程序? - Can't unit test a method which calls a static method, how can I re-design this program? C#单元测试-测试返回方法 - C# Unit Test - Test return method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM