Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

Unit Testing and Mocking SubscriberClient (Google Pub/Sub) in a C# Project

I'm using Google Cloud Pub/Sub (Google.Cloud.PubSub.V1 (2.2.0)) in a .NET Core 3.1 project. I'm trying to write a unit test for the code that retrieves messages from a Google Pub/Sub subscription. My code is similar to what you find in the Google documentation.

var subscriber = await SubscriberClient.CreateAsync(subscriptionName);

try
{
    var startTask = subscriber.StartAsync(async (PubsubMessage message, CancellationToken cancel) =>
    {
            //code
    });
    
    await Task.Delay(5000);
    await subscriber.StopAsync(CancellationToken.None);
    await startTask;
}
catch (Exception ex)
{
        //code
}

Is there a way to mock SubscriberClient in a unit test? SubscriberClient doesn't appear to have an interface. My unit tests are using NUnit (3.12.0) and Moq (4.14.5).

Any ideas would be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling SubscriberClient.Create(...) instead of .CreateAsync(...) allows you to pass in the underlying SubscriberServiceApiClient instance(s).

Edit: Apologies, the above is incorrect, it should be:

Instantiate a SubscriberClientImpl directly instead of calling SubscriberClient.CreateAsync(...). This allows you to pass in the underlying SubscriberServiceApiClient instance(s). Note that you can pass new SubscriberClient.Settings() for the settings argument, and null for the shutdown argument as defaults.

SubscriberServiceApiClient can be mocked - either directly, or by instantiated a SubscriberServiceApiClientImpl instance and passing in a mocked Subscriber.SubscriberClient.

When testing, note that SubscriberClient is multi-threaded and with default settings will call the callback passed to StartAsync concurrently from multiple threads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...