如何为单元测试模拟Azure队列存储?

3hvapo4f  于 2023-02-05  发布在  其他
关注(0)|答案(4)|浏览(128)

我想模拟QueueMessage进行单元测试,但找不到任何要模拟的库

public  async Task<QueueMessage[]> ReceiveMessagesAsync(QueueClient queue)
       {
     
        QueueProperties properties = queue.GetProperties();

        // Retrieve the cached approximate message count.
        int cachedMessagesCount = properties.ApproximateMessagesCount;
        QueueMessage[] queueMessages =new QueueMessage[cachedMessagesCount];

        int num = cachedMessagesCount / 32;

        for (int i = 0; i < num + 1; i++)
        {
         var  messages = await queue.ReceiveMessagesAsync(maxMessages: 32);
         messages.Value.CopyTo(queueMessages,i*32);
        }
        return queueMessages;
    }
ffscu2ro

ffscu2ro1#

选择Mocking lib可能是一个固执己见的答案。有几个Mocking框架可用。其中一个流行的是Moq
使用Moq,上面代码的示例测试如下所示。请注意,模拟存储库是一项有点乏味的任务。

[Test]
        public async Task ReceiveMessagesAsync_StateUnderTest_ExpectedBehavior()
        {
            // Arrange
            var queueClientHelper = new QueueClientHelper();
            var queueMock = new Mock<QueueClient>();
            var mockPropertiesResponse = new Mock<Response<QueueProperties>>();
            var properties = new QueueProperties();
            properties.GetType().GetProperty(nameof(properties.ApproximateMessagesCount), BindingFlags.Public | BindingFlags.Instance).SetValue(properties, 64); // little hack since ApproximateMessagesCount has internal setter
            mockPropertiesResponse.SetupGet(r => r.Value).Returns(properties);
            queueMock.Setup(q => q.GetProperties(It.IsAny<CancellationToken>())).Returns(mockPropertiesResponse.Object);
            var mockMessageReponse = new Mock<Response<QueueMessage[]>>();
            mockMessageReponse.SetupGet(m => m.Value).Returns(new QueueMessage[32]);
            queueMock.Setup(q => q.ReceiveMessagesAsync(It.IsAny<int?>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockMessageReponse.Object);

            // Act
            var result = await queueClientHelper.ReceiveMessagesAsync(queueMock.Object);

            // Assert
            Assert.AreEqual(64, result.Length);
            // verify mocks as required
        }
wwwo4jvm

wwwo4jvm2#

Queue模型的构造函数是内部的,但是您可以使用QueuesModelFactory创建对象,QueuesModelFactory提供了用于模拟的实用程序。

QueueMessage queueMsg = QueuesModelFactory.QueueMessage(
    messageId: "id2", 
    popReceipt: "pr2", 
    body: JsonConvert.SerializeObject("Test"), 
    dequeueCount: 1, 
    insertedOn: DateTimeOffset.UtcNow);

 var metadata = new Dictionary<string, string> { { "key", "value" }, };
 int messageCount = 5;
 QueueProperties queueProp = QueuesModelFactory.QueueProperties(metadata, messageCount);
relj7zay

relj7zay3#

尝试模拟queueClient的响应,这将验证sendMessageAsync响应

[Fact]
    public async Task SendMessage_ShouldReturnSuccess()
    {
        var receipt = QueuesModelFactory.SendReceipt("1", DateTimeOffset.Now, DateTimeOffset.Now.AddDays(2), "pop", DateTimeOffset.Now.AddDays(1));
        var res = Response.FromValue<SendReceipt>(receipt, null);
        var queueClientmock = new Mock<QueueClient>();
        queueClientmock.Setup(q => q.SendMessageAsync(It.IsAny<string>())).Returns(Task.FromResult(res));
        var sqmock = new Mock<IStorageQueueProvider>();
        sqmock.Setup(s => s.GetStorageQueueClient()).Returns(Task.FromResult(queueClientmock.Object)).Verifiable();
        var storageQueueRepository = new StorageQueueRepository(sqmock.Object, DummyLogger);
        var result = await storageQueueRepository.SendMessage("test message");
        result.StatusCode.Should().Be(HttpStatusCode.OK);
    }
sbtkgmzw

sbtkgmzw4#

return QueuesModelFactory.QueueMessage(
            messageId: "id2",
            popReceipt: "pr2",
            body: BinaryData.FromString(encode ? Convert.ToBase64String(Encoding.UTF8.GetBytes(Message)) : Message),
            dequeueCount: dequeueCount,
            insertedOn: DateTimeOffset.UtcNow);

相关问题