【问题标题】:Add additional method to service in unit tests在单元测试中为服务添加额外的方法
【发布时间】:2020-08-26 08:27:57
【问题描述】:

我们正在使用.NET Core 3.1。我们想测试是否将正确的消息作为参数传递给我们的电子邮件服务。可能要走的路是模拟Send 方法并将消息保存到内存队列/列表中。我们如何在不修改原始界面(IEmailService)的情况下做到这一点?在我们的模拟服务中,我们需要一个额外的方法,它返回传递给它的Send 方法的所有消息,比如List<Message> GetSentEmails()。

TestsBase.cs

public class TestsBase
{
    protected readonly IServiceScope _scope;
    protected readonly IPaymentService _paymentService;
    protected readonly IEmailService _emailService;
    
    public TestsBase(CustomWebApplicationFactory<Startup> factory)
    {
        _scope = factory.Services.CreateScope();
        _paymentService = _scope.ServiceProvider.GetService<IPaymentService>();
        _emailService = _scope.ServiceProvider.GetService<IEmailService>() as EmailServiceMock;
    }
}

[CollectionDefinition("MyCollection")]
public class MyCollection : ICollectionFixture<CustomWebApplicationFactory<Startup>>
{

}

PaymentServiceTest.cs

[Collection("MyCollection")]
public class PaymentServiceTest : TestsBase
{
    public PaymentServiceTest(CustomWebApplicationFactory<Startup> factory) : base(factory)
    {

    }
    
    [Fact]
    public void ConfirmPaymentTest()
    {
        // payment service also sends email
        _paymentService.Process(new Payment()
        {
            Amount = 203.12,
            Email = "test@test.com",
            ...
        });
        
        // we want to check if correct email was passed to email service
        var sentEmails = _emailService.GetSentEmails(); // HOW?
    }
}

CustomWebApplicationFactory.cs

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            // mock email service
            services.AddScoped<IEmailService, EmailServiceMock>();
        });
    }
}

EmailService.cs

public class EmailService : IEmailService
{
    // implementation
}

public class EmailServiceMock : IEmailService
{
    private readonly List<Message> _sentEmails;

    public EmailServiceMock()
    {
        _sentEmails = new List<Message>();
    }
    
    // mocked implementation of all the methods
    // but we also need access to _sentEmails
    
    public void Send(Message message)
    {
        _sentEmails.Add(message);
    }
}

【问题讨论】:

  • 如您所说,您需要在EmailServiceMock 中为_sentEmails 添加访问方法/属性。

标签: c# unit-testing asp.net-core mocking


【解决方案1】:

我建议您为此使用 Moq 库。您可以模拟您的 IEmailService 并使用 Moq 的 Callback 方法来捕获传递给 Send 方法的参数。

您只需要调整服务的初始化。

[Fact]
public void ConfirmPaymentTest()
{
    var sentEmails = new List<Message>();
    var emailService = new Mock<IEmailService>();
    var paymentService = new PaymentService(emailService.Object);
    
    emailService
        .Setup(e => e.Send(It.IsAny<Message>()))
        .Callback<Message>(m => sentEmails.Add(m));   // instead of your GetSentEmails()
    
    paymentService.Process(new Payment()
    {
        Amount = 203.12,
        Email = "test@test.com",
        ...
    });
    
    // you can access your sentEmails list here
}

Moq 是一个非常强大的 .NET 测试库。还有更多功能可以让您模拟方法的返回、验证方法被调用的次数等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多