奇怪的异常测试EmailSender

时间:2019-03-20 14:43:51

标签: asp.net testing asp.net-core integration-testing

我刚刚遵循了所有有关在ASP.NET Core 3.0 MVC应用程序中构建Identity UI的MS说明。如果我运行该项目,它将打开默认的主页,并且该页面上的链接响应良好。但是,简单的集成测试会失败,并有例外。

EmailSender中的单个方法如下:

public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
    using (var client = new SmtpClient())
    using (var msg = new MailMessage())
    {
        msg.From = new MailAddress("system@timekeeper.co.za");
        msg.To.Add(new MailAddress(email));
        msg.Subject = subject;
        msg.IsBodyHtml = true;

        client.UseDefaultCredentials = false;
        client.Credentials = new NetworkCredential("timekeeper@somewhere.com", "something");
        client.Host = "mail.myhost.com";
        client.Port = 25;
        return client.SendMailAsync(msg);
    }
}

我的测试如下:

[TestMethod]
public async Task Send_Email()
{
    var sender = new EmailSender();

    await sender.SendEmailAsync("somebody@somewhere.net", "Test Mail", "This is a test");

    Assert.IsTrue(true);
}

我运行测试时失败,但出现以下异常:

Test method TimeKeeper.Tests.Integration.EmailSEnderTests.Send_Email threw exception: 
System.Threading.Tasks.TaskCanceledException: A task was canceled.
    at TimeKeeper.Tests.Integration.EmailSEnderTests.Send_Email() in D:\Dev\RestServices\TimeKeeper.Tests.Integration\EmailSEnderTests.cs:line 15
   at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action action)

1 个答案:

答案 0 :(得分:0)

await而不是返回任务。

public async Task SendEmailAsync(string email, string subject, string htmlMessage) {
    using (var client = new SmtpClient())
    using (var msg = new MailMessage()) {
        msg.From = new MailAddress("system@timekeeper.co.za");
        msg.To.Add(new MailAddress(email));
        msg.Subject = subject;
        msg.IsBodyHtml = true;

        client.UseDefaultCredentials = false;
        client.Credentials = new NetworkCredential("timekeeper@somewhere.com", "something");
        client.Host = "mail.myhost.com";
        client.Port = 25;
        await client.SendMailAsync(msg); //<-- await completion
    }
}

有可能client在有机会完成发送电子邮件之前被处理掉了。

您还应该注意文档中关于将现在已经过时的 SmtpClient用于新开发的警告。

  

DE0005:不应使用SmtpClient

     

动机

     

SmtpClient不支持许多现代协议。它仅兼容。这非常适合使用工具发送的电子邮件,但不适合   可以适应该协议的现代要求。

     

推荐

     

使用MailKit或其他库。