简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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