[英]How to Write unit test Code for sending Message to Azure ServiceBus Topic?
我在 Azure 函數中編寫了將消息從 Servicebus 隊列發送到 ServiceBus 主題的代碼。 在為此編寫單元測試用例時遇到問題。 如何編寫用於創建虛擬服務總線主題連接字符串的單元測試用例
我已成功完成將消息發送到服務總線隊列的代碼,但無法獲得服務總線主題的確切代碼
您將需要模擬您正在調用的任何外部服務或 class,因為單元測試不是集成測試。
例如,如果使用這樣的文件系統:
public class Foo {
public void SaveFile(string fileName) {
File.WriteAllText(fileName, "did something");
}
}
要對此進行單元測試,您可以使用適配器模式,然后可以對其進行模擬。
public interface IFileSystem {
void WriteAllText(string fileName, string text);
}
public class FileSystemAdapter : IFileSystem {
public void WriteAllText(string fileName, string text) {
File.WriteAllText(fileName, text);
}
}
然后在你的 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");
}
}
使用 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.