Код: Выделить всё
using NotificationJob.Service.Email.SendGrid;
using NotificationJob.Service.Email.Settings;
using Microsoft.Extensions.Options;
using SendGrid;
using SendGrid.Helpers.Mail;
using Response = SendGrid.Response;
namespace NotificationJob.Service;
public class EmailService(
IOptions emailAlertSettings,
ILogger logger
) : IEmailService
{
private readonly Settings emailAlertSettings = emailAlertSettings.Value;
private ILogger _logger { get; } = logger;
public async Task SendEmail(string to, string subject, string body, string displayName, bool isSandbox=false)
{
var apiKey = emailAlertSettings.SendGridKey;
var eNotificationSenderEmailId = emailAlertSettings.ENotificationSenderEmailId;
var client = new SendGridClient(apiKey);
SendGridMessage sendMail = new SendGridMessage();
sendMail.From = new EmailAddress(eNotificationSenderEmailId);
sendMail.Subject = subject;
sendMail.AddTo(new EmailAddress(to, displayName));
string result = string.Empty;
//Enable Sandbox for testing based on config value
if (isSandbox)
{
sendMail.SetSandBoxMode(true);
}
try
{
sendMail.HtmlContent = body;
var response = await client.SendEmailAsync(sendMail);
_logger.LogInformation($"Email sent {to} subject {subject} displayName {displayName} @{DateTime.UtcNow}: with status code: {response.IsSuccessStatusCode}");
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error sending email to {to} subject {subject} displayName {displayName} @{DateTime.UtcNow}: {ex.Message}");
throw;
}
}
}
Код: Выделить всё
public class EmailServiceTests
{
private Mock _mockSettings;
private Mock _mockLogger;
private EmailService _emailService;
public EmailServiceTests()
{
_mockSettings = new Mock();
_mockLogger = new Mock();
}
[Fact]
public async Task SendEmail_Success_LogsAndReturnsResponse()
{
// Arrange
var to = "recipient@example.com";
var subject = "Test Email";
var body = "This is a test email body.";
var displayName = "Test User";
var apiKey = "your_api_key"; // Replace with actual API key
var senderEmailId = "sender@example.com";
_mockSettings.Setup(s => s.Value.SendGridKey).Returns(apiKey);
_mockSettings.Setup(s => s.Value.ENotificationSenderEmailId).Returns(senderEmailId);
var mockResponse = new Mock();
mockResponse.Setup(r => r.IsSuccessStatusCode).Returns(true);
var mockClient = new Mock(apiKey);
mockClient.Setup(c => c.SendEmailAsync(It.IsAny()))
.Returns(Task.FromResult(mockResponse.Object));
_emailService = new EmailService(_mockSettings.Object, _mockLogger.Object);
// Act
var response = await _emailService.SendEmail(to, subject, body, displayName);
// Assert
mockClient.Verify(c => c.SendEmailAsync(It.IsAny()), Times.Once);
_mockLogger.Verify(l => l.LogInformation(
It.Is(s => s.Contains(subject) && s.Contains(displayName))), Times.Once);
Assert.NotNull(response);
Assert.True(response.IsSuccessStatusCode);
}
}
System.NotSupportedException: неподдерживаемое выражение: r => r.IsSuccessStatusCode
Непереопределяемые члены (здесь: Response.get_IsSuccessStatusCode) не могут использоваться в выражениях настройки/проверки.
Проверено снова получаю это
Сообщение:
System.NotSupportedException: Неподдерживаемое выражение: c => c.SendEmailAsync(It.IsAny(), CancellationToken.None)
Непереопределяемые члены (здесь: BaseClient. SendEmailAsync) нельзя использовать в выражениях настройки/проверки.
Пожалуйста, сообщите, как мне настроить ложный ответ
Подробнее здесь: https://stackoverflow.com/questions/784 ... d-response
Мобильная версия