简体   繁体   English

如何编写用于向 Azure ServiceBus 主题发送消息的单元测试代码?

[英]How to Write unit test Code for sending Message to Azure ServiceBus Topic?

I have written code for sending messages from Servicebus Queue to ServiceBus topic in Azure Functions.我在 Azure 函数中编写了将消息从 Servicebus 队列发送到 ServiceBus 主题的代码。 Am getting issues while writing unit test cases for the same.在为此编写单元测试用例时遇到问题。 How to write unit test case for creating dummy servicebus topic connection string如何编写用于创建虚拟服务总线主题连接字符串的单元测试用例

I have done the code for sending message to servicebus queue successfully but am not able to get exact code for servicebus topic我已成功完成将消息发送到服务总线队列的代码,但无法获得服务总线主题的确切代码

You will need to mock any external service or class that you are calling, as a unit test is not an integration test.您将需要模拟您正在调用的任何外部服务或 class,因为单元测试不是集成测试。

For example if using the file system like this:例如,如果使用这样的文件系统:

public class Foo {
  public void SaveFile(string fileName) {
    File.WriteAllText(fileName, "did something");
  }
}

To unit test this you can use an adapter pattern which you can then mock.要对此进行单元测试,您可以使用适配器模式,然后可以对其进行模拟。

public interface IFileSystem {
  void WriteAllText(string fileName, string text);
}

public class FileSystemAdapter : IFileSystem {
  public void WriteAllText(string fileName, string text) {
    File.WriteAllText(fileName, text);
  }
}

Then in your Foo Class use the Interface and in your test you mock it using a mock framework like NSubstitute然后在你的 Foo Class 中使用接口,在你的测试中你使用像 NSubstitute 这样的模拟框架模拟它

public class Foo {
  readonly IFileSystem fileSystem;

  public Foo() : this(new FileSystemAdapter()) {}
  internal Foo(IFileSystem fileSystem) {
    this.fileSystem = fileSystem;
  }

  public void SaveFile(string fileName) {
    fileSystem.WriteAllText(fileName, "did something");
  }
}

Your test could like like this using NUnit/NSubstitute:使用 NUnit/NSubstitute,您的测试可能会像这样:

public class FooTest {
  [Test]
  public void SaveFileCallsWriteAllText() {
    IFileSystem mockFileSystem = Substitute.For<IFileSystem>();
    var testObj = new Foo(mockFileSystem);
    testObj.SaveFile("testFile");
    mockFileSystem.Received(1).WriteAllText(Arg.Is<string>("testFile"), Arg.Is<string>("did something"));
  }
}

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

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