2

I am trying to unit test Microsoft.Azure.ServiceBus(3.3.0) topic and subscription functionality. But I am not interested in testing Microsoft.Azure.ServiceBus classes, but more how mock Send a message to the topic and check if that message exists on that specific topic with a subscription.

At the moment I have a super simple Publisher class with one method SendAsync. As you can see here:

// Pseudo code, not full implementation!

public class Publisher : IPublisher
{
    private readonly ManagementClient _managementClient;
    private readonly TopicClientFactory _topicClientFactory;

    public Publisher(ManagementClient managementClient, TopicClientFactory topicClientFactory)
    {
        _managementClient = managementClient;
        _topicClientFactory = topicClientFactory;
    }

    public async Task SendAsync(myModel message)
    {
        ITopicClient topicClient = _topicClientFactory.Create("MyTopic");

        // encode message using message

        Message message = new Message(encodedMessage);
        await topicClient.SendAsync(message); // trying to mock & test this!
        await topicClient.CloseAsync();
    }
}

Factory has only one method. When creating a new TopicClient using factory I am also returning the ITopicClient interface. Not sure if that helps.

// Pseudo code, not full implementation!
public class TopicClientFactory
{
    public ITopicClient Create(string topicPath)
    {
        return new TopicClient("MyConnectionString", topicPath);
    }
}

Unit test:

[Fact]
public async Task Name()
{
    var managementClientMock = new Mock<ManagementClient>("MyConnectionString");
    var topicClientFactoryMock = new Mock<TopicClientFactory>("MyConnectionString");

    // mock topic client's send method!
    var topicClientMock = new Mock<ITopicClient>();
    topicClientMock.Setup(x =>
        x.SendAsync(It.IsAny<Message>())).Returns(Task.CompletedTask); // .Verifiable();

    // pass mocked topicClient to mocked factory
    topicClientFactoryMock.Setup(tc => tc.Create("topicPath")).Returns(topicClientMock.Object);

    var publisher = new Publisher(managementClientMock.Object, topicClientFactoryMock.Object);

    await publisher.SendAsync(command);

    // how to test if message has been sent?
}
kerpekri
  • 346
  • 7
  • 19
  • It looks like this could be connected to what I want to achieve - https://stackoverflow.com/questions/47197897/unit-test-using-moq-nested-class-interface-c-sharp?rq=1 – kerpekri Apr 06 '20 at 08:44

0 Answers0