Please find my service class
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<Settings> emailAlertSettings,
ILogger<EmailService> logger
) : IEmailService
{
private readonly Settings emailAlertSettings = emailAlertSettings.Value;
private ILogger<EmailService> _logger { get; } = logger;
public async Task<Response> 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;
}
}
}
Pease find the unit test
public class EmailServiceTests
{
private Mock<IOptions<Settings>> _mockSettings;
private Mock<ILogger<EmailService>> _mockLogger;
private EmailService _emailService;
public EmailServiceTests()
{
_mockSettings = new Mock<IOptions<Settings>>();
_mockLogger = new Mock<ILogger<EmailService>>();
}
[Fact]
public async Task SendEmail_Success_LogsAndReturnsResponse()
{
// Arrange
var to = "[email protected]";
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 = "[email protected]";
_mockSettings.Setup(s => s.Value.SendGridKey).Returns(apiKey);
_mockSettings.Setup(s => s.Value.ENotificationSenderEmailId).Returns(senderEmailId);
var mockResponse = new Mock<Response>();
mockResponse.Setup(r => r.IsSuccessStatusCode).Returns(true);
var mockClient = new Mock<SendGridClient>(apiKey);
mockClient.Setup(c => c.SendEmailAsync(It.IsAny<SendGridMessage>()))
.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<SendGridMessage>()), Times.Once);
_mockLogger.Verify(l => l.LogInformation(
It.Is<string>(s => s.Contains(subject) && s.Contains(displayName))), Times.Once);
Assert.NotNull(response);
Assert.True(response.IsSuccessStatusCode);
}
}
The problem is getting error in mockResponse.Setup(r => r.IsSuccessStatusCode).Returns(true);
as
System.NotSupportedException : Unsupported expression: r => r.IsSuccessStatusCode
Non-overridable members (here: Response.get_IsSuccessStatusCode) may not be used in setup / verification expressions.
Please advise how can i setup mock Response