Мой код выглядит следующим образом:
Код: Выделить всё
using Azure.Storage.Queues;
using my_api.Helpers;
namespace nlp_api.Services.Azure
{
public interface IAzureQueueService
{
Task SendMessageAsync(string message);
}
public class AzureQueueService : IAzureQueueService
{
private readonly QueueClient _queueClient;
private readonly ILogger _logger;
public AzureQueueService(IConfiguration configuration, ILogger logger, IAzureCredentialHelper azureCredentialHelper)
{
_logger = logger;
// Get the Azure Storage Account URL and queue name from configuration
var accountUrl = configuration["AzureConnection:QueueStorageUrl"];
var queueName = configuration["AzureConnection:QueueName"];
// Use the AzureCredentialHelper to get the appropriate TokenCredential
var credential = azureCredentialHelper.GetCredential();
// Create a QueueServiceClient and then retrieve the specific queue client
_queueClient = new QueueClient(new Uri($"{accountUrl}/{queueName}"), credential);
}
public async Task SendMessageAsync(string message)
{
try
{
// Send the plain-text message to the Azure Queue
await _queueClient.SendMessageAsync(message);
_logger.LogInformation("Successfully sent message to queue.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred while sending message to the queue.");
throw;
}
}
}
}
Код: Выделить всё
using Azure.Storage.Queues;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using my_api.Services.Azure;
using Azure.Core;
using my_api.Helpers;
namespace nlp_api.UnitTests.Services.Azure
{
public class AzureQueueServiceTests
{
[Fact]
public async Task SendMessageAsync_Successfully_Sends_Message()
{
// Arrange
var mockQueueClient = new Mock("https://mockstorageaccount.queue.core.windows.net", "mock-queue");
var mockLogger = new Mock();
var mockCredentialHelper = new Mock();
// Mock GetCredential to return a fake credential
var mockTokenCredential = new Mock();
mockCredentialHelper.Setup(helper => helper.GetCredential()).Returns(mockTokenCredential.Object);
var mockConfiguration = new Mock();
mockConfiguration.Setup(c => c["AzureConnection:QueueStorageUrl"]).Returns("https://mockstorageaccount.queue.core.windows.net");
mockConfiguration.Setup(c => c["AzureConnection:QueueName"]).Returns("mock-queue");
var queueService = new AzureQueueService(mockConfiguration.Object, mockLogger.Object, mockCredentialHelper.Object);
// Mock the SendMessageAsync method to just complete without error
mockQueueClient.Setup(client => client.SendMessageAsync(It.IsAny(), default));
// Act
await queueService.SendMessageAsync("Test message");
// Assert
mockQueueClient.Verify(client => client.SendMessageAsync(It.Is(msg => msg == "Test message"), default), Times.Once);
mockLogger.Verify(logger => logger.LogInformation(It.IsAny()), Times.Once);
}
}
}
Можно ли как-нибудь издеваться над этим QueueClient при его создании в конструкторе? Я попытался создать своего рода класс-оболочку для создания QueueClient и передать эту оболочку в конструктор моего класса AzureQueueService, что делает класс тестируемым. Однако теперь у меня есть класс-оболочка, который мне нужно протестировать, в конструкторе которого снова создается QueueClient, поэтому я столкнулся с той же проблемой. Кроме того, создание этой оболочки кажется слишком накладным только для того, чтобы сделать мой класс тестируемым.
Есть ли какой-нибудь чистый и аккуратный способ позволить мне имитировать экземпляр QueueClient внутри конструктора AzureQueueService класс?
Подробнее здесь: https://stackoverflow.com/questions/793 ... -unit-test
Мобильная версия