Reputation: 11
I have written code for sending messages from Servicebus Queue to ServiceBus topic in Azure Functions. 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
Upvotes: 0
Views: 528
Reputation: 535
You will need to mock any external service or class that you are calling, as a unit test is not an integration test.
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
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:
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"));
}
}
Upvotes: 2