我正在尝试对 Microsoft.Azure.ServiceBus(3.3.0) 主题和订阅功能进行单元测试。但我对测试 Microsoft.Azure.ServiceBus 类不感兴趣,但更多的是如何模拟向主题发送消息并检查该消息是否存在于带有订阅的特定主题上。
目前我有一个超级简单的 Publisher 类,它有一个方法 SendAsync。正如你在这里看到的:
// Pseudo code, not full implementation!
public class Publisher : IPublisher
{
private readonly ManagementClient _managementClient;
private readonly TopicClientFactory _topicClientFactory;
public Publisher(ManagementClient managementClient, TopicClientFactory topicClientFactory)
{
_managementClient = managementClient;
_topicClientFactory = topicClientFactory;
}
public async Task SendAsync(myModel message)
{
ITopicClient topicClient = _topicClientFactory.Create("MyTopic");
// encode message using message
Message message = new Message(encodedMessage);
await topicClient.SendAsync(message); // trying to mock & test this!
await topicClient.CloseAsync();
}
}
工厂只有一种方法。使用工厂创建新的 TopicClient 时,我还返回了 ITopicClient 接口。不确定这是否有帮助。
// Pseudo code, not full implementation!
public class TopicClientFactory
{
public ITopicClient Create(string topicPath)
{
return new TopicClient("MyConnectionString", topicPath);
}
}
单元测试:
[Fact]
public async Task Name()
{
var managementClientMock = new Mock<ManagementClient>("MyConnectionString");
var topicClientFactoryMock = new Mock<TopicClientFactory>("MyConnectionString");
// mock topic client's send method!
var topicClientMock = new Mock<ITopicClient>();
topicClientMock.Setup(x =>
x.SendAsync(It.IsAny<Message>())).Returns(Task.CompletedTask); // .Verifiable();
// pass mocked topicClient to mocked factory
topicClientFactoryMock.Setup(tc => tc.Create("topicPath")).Returns(topicClientMock.Object);
var publisher = new Publisher(managementClientMock.Object, topicClientFactoryMock.Object);
await publisher.SendAsync(command);
// how to test if message has been sent?
}