简体   繁体   English

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

[英]How to mock Azure Queue storage for unit test?

I want to mock QueueMessage for unit test,but I can not find any lib to mock我想模拟 QueueMessage 进行单元测试,但我找不到任何 lib 来模拟

    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;
    }

Choice of Mocking lib would be an opinionated answer.选择 Mocking lib 将是一个固执的答案。 There are several mocking frameworks available.有几个 mocking 框架可用。 One of the popular ones is Moq .最受欢迎的之一是Moq

Using Moq, the sample test for your above code would look like below.使用 Moq,上述代码的示例测试如下所示。 Note that mocking storage lib is a bit tedious task as you can see.请注意,如您所见,mocking 存储库是一个有点乏味的任务。

        [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
        }

The constructors of the Queue models are internal, but you can create objects using the QueuesModelFactory which provides utilities for mocking.队列模型的构造函数是内部的,但您可以使用为mocking提供实用程序的 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);

Try to mock the response of queueClient this will verify sendMessageAsync response尝试模拟 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);
    }
        return QueuesModelFactory.QueueMessage(
            messageId: "id2",
            popReceipt: "pr2",
            body: BinaryData.FromString(encode ? Convert.ToBase64String(Encoding.UTF8.GetBytes(Message)) : Message),
            dequeueCount: dequeueCount,
            insertedOn: DateTimeOffset.UtcNow);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何模拟参数请求单元测试谷歌云 function? - How to mock params request unit test google cloud function? 如何使用 SAS 向存储队列验证 Azure REST API? - How to authenticate Azure REST APIs to Storage Queue with SAS? 如何修改 azure 管道中测试结果的存储库/存储位置 - How to modify the repository / storage location for Test Results in azure pipeline Python:检查Azure队列存储是否存在 - Python: Check if Azure queue storage exists 单元测试 Azure 事件中心触发器(Azure 函数) - Unit test Azure Event Hub Trigger (Azure Function) 为 Microsoft Azure Blob 存储自动化 Snowpipe - 错误:找不到通道的队列 - Automating Snowpipe for Microsoft Azure Blob Storage - error: Queue not found for channel Databricks:Azure Queue Storage structured streaming key not found 错误 - Databricks: Azure Queue Storage structured streaming key not found error 如何在本地模拟和测试 Databricks Pyspark 笔记本 - How to mock and test Databricks Pyspark notebooks Locally azure function 重试场景的单元测试用例 - nodejs - azure function unit test cases for retry scenario - nodejs 如何在反应单元测试中模拟 aws-amplify? - How to mock aws-amplify in react unit testing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM