简体   繁体   English

Azure服务总线抛出瞬态异常时如何使用xUnit测试代码

[英]How to use xUnit to test code when Azure Service bus throws Transient exceptions

I have an Azure Service Bus Trigger function that has the job of replicating the incoming message from a topic and sending it to another service bus topic.我有一个 Azure 服务总线触发器 function 负责复制来自主题的传入消息并将其发送到另一个服务总线主题。

I send the incoming message to the service bus in the other region using Azure.Messaging.ServiceBus.ServiceBusSender.SendMessageAsync()我使用 Azure.Messaging.ServiceBus.ServiceBusSender.SendMessageAsync() 将传入消息发送到其他区域的服务总线

I need to write a xUnit test to ensure the right behaviour is being followed when the topic/service bus in the other region is unavailable.我需要编写一个 xUnit 测试,以确保在其他区域的主题/服务总线不可用时遵循正确的行为。 Is there a way to simulate the SendMessageAsync() method throwing one of the transient exceptions to test this?有没有办法模拟 SendMessageAsync() 方法抛出一个瞬态异常来测试这个?

You can mock ServiceBusSender.您可以模拟 ServiceBusSender。

eg using NSubstitute + xUnit例如使用 NSubstitute + xUnit

[Fact]
public void Test1()
{
    // Arrange
    var mockSender = Substitute.For<ServiceBusSender>();
    mockSender.SendMessageAsync(default).ThrowsForAnyArgs(new Exception("Example exception"));

    // Act
    var testClass = new YourClass(mock);
    testClass.DoSomething();

    // Assert
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM