我有下一个方法,请注意我正在执行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/