使用 xUnit 和 Moq 在 .NET 5 中对 FluentEmail 进行单元测试

阿什K。

我正在尝试对FluentEmail进行单元测试,但我一直收到null发送响应。

这是它在ConfigureServices方法中的设置方式:

// Set email service using FluentEmail
services.AddFluentEmail("[email protected]")
        // For Fluent Email to find _Layout.cshtml, just mention here where your views are.
        .AddRazorRenderer(@$"{Directory.GetCurrentDirectory()}/Views/")
        .AddSmtpSender("smtp.somecompanyname.com", 25)
        .AddSmtpSender(new System.Net.Mail.SmtpClient() { });

现在电子邮件服务看起来像这样:

public class FluentEmailService : IFluentEmailService
{
    private readonly IFluentEmail _fluentEmail;
    private readonly ILogger<FluentEmailService> _logger;
    public FluentEmailService(ILogger<FluentEmailService> logger, IFluentEmail fluentEmail)
    {
        _logger = logger;
        _fluentEmail = fluentEmail;
    }

    public async Task<SendResponse> SendEmailAsync<TModel>(string subject, string razorTemplatePath, TModel model, string semicolonSeparatedEmailRecipients)
    {
        try
        {
            var sendResponse = await _fluentEmail
                            .To(semicolonSeparatedEmailRecipients)
                            .Subject(subject)
                            .UsingTemplateFromFile(razorTemplatePath, model)
                            .SendAsync();
            return sendResponse;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to send email. Check exception for more information.");
            return new SendResponse() { ErrorMessages = new string[] { ex.Message } };
        }
    }
}

我的测试方法如下所示:

[Fact]
public async Task Can_Verify_FluentEmail_WORKS_Async()
{
    // ARRANGE
    var mockFluentEmail = new Mock<IFluentEmail>();

    mockFluentEmail.Setup(m => m.To(It.IsAny<string>())).Returns(mockFluentEmail.Object);
    mockFluentEmail.Setup(m => m.Subject(It.IsAny<string>())).Returns(mockFluentEmail.Object);
    mockFluentEmail.Setup(m => m.UsingTemplateFromFile(It.IsAny<string>(), It.IsAny<It.IsAnyType>(), It.IsAny<bool>())).Returns(mockFluentEmail.Object);

    //Create FluentEmail service using fake logger and IFluentEmail
    var fakeLogger = Mock.Of<ILogger<FluentEmailService>>();
    var fluentEmailService = new FluentEmailService(fakeLogger, mockFluentEmail.Object);

    // ACT
    var sendResponse = await fluentEmailService.SendEmailAsync("Test Subject", "Some Path", It.IsAny<It.IsAnyType>(), "Some Recipient");
    
    // ASSERT
    Assert.NotNull(sendResponse);
    Assert.True(sendResponse.Successful);
    mockFluentEmail.Verify(f => f.To("Some Recipient"), Times.Once(), "Recipient should be set as: 'Some Recipient'.");
    mockFluentEmail.Verify(f => f.Subject("Test Subject"), Times.Once, "Subject should be set as: 'Test Subject'.");
    mockFluentEmail.Verify(f => f.UsingTemplateFromFile("Some Path", It.IsAny<It.IsAnyType>(), It.IsAny<bool>()), Times.Once, "Path should be set as: 'Some Path'.");
    mockFluentEmail.Verify(f => f.SendAsync(null), Times.Once, "1 email should be sent.");
}

测试总是失败,因为我得到nullsendResponse.

有人可以告诉我我这样做是否正确?

尤金

这可能是因为最后一个函数调用SendAsync没有被模拟,因此默认返回 null。

由于它是异步调用,因此使用ReturnsAsync而不是Returns.

ReturnsAsync还应该返回一个实际的SendResponse

//...

SendResponse expectedSendResponse = new SendResponse();

mockFluentEmail
   .Setup(m => m.SendAsync(null))
   .ReturnsAsync(expectedSendResponse);

//...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Xunit对ASP.net中的[System.Web.Http.Authorize]过滤器进行单元测试

使用Moq对通用工作单元和存储库模式框架进行单元测试

使用Moq进行单元测试的工作单元和通用存储库模式框架

使用.NET Core和xUnit同时针对多个框架的单元测试代码

在使用Moq和AutoFixture进行单元测试API时模拟HttpResponseMessage

使用Moq .net Core进行单元测试文件上传

如何使用MoQ和NUnit在WebAPI 2中编写ExceptionHandler的单元测试

如何使用Moq对在.NET中使用asmx服务的应用程序进行单元测试

如何使用Entity Framework和Moq进行单元测试?

使用MOQ嵌套类和接口C#进行单元测试

使用moq通用存储库和UnitOfWork进行单元测试

使用Moq和Xunit测试接口

如何在xUnit和nSubstitute中对服务调用进行单元测试

使用Moq和xUnit对服务进行单元测试

使用Autofixture,Moq和XUnit的类中的部分模拟方法

带有Moq单元测试的Net Framework Xunit继续调用原始功能

如何使用Moq和xUnit测试异步方法

从服务获取对象以允许使用xUnit和Moq运行测试

如何使用Moq对.NET Core 3.1中的LoggerMessage.Define()进行单元测试?

使用Moq进行单元测试

使用Moq和Autofac进行单元测试

使用 Moq 框架进行单元测试

使用 Moq 和接口进行单元测试

使用 xunit 和 moq 进行 net core api 控制器单元测试

在使用 xunit 和 .net core 3.1 进行单元测试时获取记录器

如何使用 moq 和 xunit 测试业务逻辑方法?

使用 xUnit 和 FakeItEasy 对 Azure 函数 v3 进行单元测试

使用通用存储库、UnitOfWork、NUnit 和 Moq 进行单元测试

使所有 EF Core 模型属性虚拟化,以便在使用 Moq 和 xUnit 的单元测试中进行模拟?