【发布时间】: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