如何对调用服务总线队列客户端SendAsync方法的类进行单元测试

问题描述 投票:5回答:1

我有一个接口,它有一个方法来创建队列客户端和消息工厂的实例。我已经创建了相同的具体实现,现在我正在尝试单元测试用于将消息发送到队列的功能。我在下面写了相同的代码:

private readonly Mock<IQueueClientProvider> queueClientProvider;

private readonly Mock<IJsonSerializer> jsonSerializer;

private readonly Mock<ILogger<QueueConnector>> logger;

private readonly ModelLogger<QueueConnector> modelLogger;

private readonly QueueConnector queueConnector;

private readonly Mock<QueueClient> queueClient;

public QueueConnectorTests() 

{

   queueClientProvider = new Mock< IQueueClientProvider >();

   queueClient = new Mock< QueueClient >();

   logger = new Mock< ILogger< QueueConnector >>();

   jsonSerializer = new Mock< IJsonSerializer >();

   modelLogger = new ModelLogger<QueueConnector>(logger.Object,     jsonSerializer.Object);

queueConnector = new QueueConnector(modelLogger, queueClientProvider.Object);

}

[Fact]
public async void ShouldBeAbleToSendMessage()

{

  BrokeredMessage brokeredMessage = new BrokeredMessage();

brokeredMessage.CorrelationId = "0HKVUFCD6Q5JL";

queueClientProvider.Setup(q =>q.CreateQueueClient()).Returns(queueClient.Object);

// Act

await queueConnector.SendMessage(brokeredMessage);

// Assert

 queueClient.Verify(q => q.SendAsync(brokeredMessage));


}

但得到例外

mscorlib.dll中出现“System.NotSupportedException”类型的异常,但未在用户代码中处理

附加信息:Parent没有默认构造函数。必须显式定义默认构造函数。

有人可以帮我这个不确定这里出错了吗?

c# unit-testing moq xunit azure-servicebus-queues
1个回答
4
投票

您应该在代码中使用IQueueClient接口而不是QueueClient实现。 SendAsync方法是ISenderClient继承的IQueueClient接口的一部分。

一旦你使用了IQueueClient,你可以这样做:

var queueClientMock = new Mock<IQueueClient>();
queueClientMock.Setup(x => 
x.SendAsync(It.IsAny<Message>))).Returns(Task.CompletedTask).Verifiable();
© www.soinside.com 2019 - 2024. All rights reserved.