c# - 如何模拟ServiceBusClient

标签 c# azure mocking

我有下一个方法,请注意我正在执行new ServiceBusClient(connectionString),我希望我可以模拟它,以便它抛出一个所需的异常。我正在使用 NSubstitute,但我不知道如何做到这一点。

 public void Connect()
        {
            try
            {
                client = new ServiceBusClient(connectionString);
            }
            catch (Exception exception)
            {
                switch (exception)
                {
                    case FormatException _:
                        logger.LogError(new ConnectionStringFormatError(connectionString));
                        break;
                    case ServiceBusException _:
                        logger.LogError(new ConnectionError(exception.Message));
                        break;
                }
            }
        }

ServiceBusClient 的构造函数有参数,因此我无法模拟类本身。有什么方法可以得到这个吗?

最佳答案

为了使此代码可测试并模拟 ServiceBusClient,您不应直接在代码中使用它,而应通过抽象来使用它。

因此,首先创建工厂的抽象,它将为您创建服务总线客户端。像这样的事情:


public interface IServiceBusClientFactory
{
   ServiceBusClient GetServiceBusClient();
}

然后你需要实现这个抽象。这个抽象的实现将创建 ServiceBusClient

的实例

public class ServiceBusClientFactory : IServiceBusClientFactory
{
    private readonly string _connStr;


    public ServiceBusClientFactory(string connStr)
    {
        if(string.IsNullOrEmpty(connStr))
        {
            throw new ArgumentNullException(nameof(connStr));
        }

        _connStr = connStr;
    }

    public ServiceBusClient GetServiceBusClient()
    {
        return new ServiceBusClient(_connStr);
    }
}

然后您的客户端代码将使用 IServiceBusClientFactory 接口(interface),您可以在单元测试中随意模拟它。

var clientMock = Substitute.For<IServiceBusClientFactory>();
clientMock.GetServiceBusClient(Arg.Any<string>()).Returns(x => throw new FormatExcepction());

当然,这需要使用 IoC - 那么您将受益于抽象的使用。

关于c# - 如何模拟ServiceBusClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76430400/

相关文章:

c# - 将委托(delegate)传递给事件 c#

c# - Linq:计算行组,包括 0 行缺失行

azure - 从 Azure DevOps 中的提交哈希获取拉取请求 ID

java - 如何在 java 8 中模拟 LocalDateTime.now()

java - 如何模拟传递给构造函数的参数

c# - 我怎样才能创建一个新的异常类并抛出它

c# - 在 Odata OrderBy 中更改字段类型

azure - 我可以将 Azure 存储帐户作为驱动器盘符装载到我的 Azure 网站吗?

azure - 在 ARM 模板中添加私有(private) nuget feed 的身份验证

c# - .NET : Usage Example? 的 Faker-cs 包