我试图从单元测试中测试事件 SmtpClient.SendCompleted 的引发,并遇到一个令人烦恼的问题:测试在事件实际触发之前继续处理,导致应用程序终止而没有实际到达事件。因此,请想象以下代码:
[TestClass]
public class emailTest
{
public bool sentEmail = false;
[TestMethod]
public void sendEmail()
{
SmtpClient smtp = new SmtpClient("smtpserver");
smtp.SendCompleted += delegate(Object sender, System.ComponentModel.AsyncCompletedEventArgs e) { sentEmail = true; };
MailMessage mm = new MailMessage("from@address.com", "to@address.com", "test subject", "test body");
smtp.SendAsync(mm, "test");
Assert.IsTrue(sentEmail);
}
}
如果我手动插入延迟,那么这个测试就会失败...
[TestClass]
public class emailTest
{
public bool sentEmail = false;
[TestMethod]
public void sendEmail()
{
SmtpClient smtp = new SmtpClient("smtpserver");
smtp.SendCompleted += delegate(Object sender, System.ComponentModel.AsyncCompletedEventArgs e) { sentEmail = true; };
MailMessage mm = new MailMessage("from@address.com", "to@address.com", "test subject", "test body");
smtp.SendAsync(mm, "test");
System.Threading.Thread.Sleep(50000); // Manual Delay
Assert.IsTrue(sentEmail);
}
}
然后测试通过。
将方法 await smtp.SendAsync 包装为任务似乎并不起作用,因为我实际上并没有等待 SendAsync 完成,而是在尝试等待 SendCompleted 执行完毕后才继续进行测试,但我不确定该如何做。
基于时间的原因,只等待 SendCompleted 处理完成所需的最少时间非常重要。
我进行了大量搜索,但似乎找不到解决此特定问题的任何资料。
快速编辑:在所有情况下,电子邮件都成功发送,只有测试失败。
SmtpClient
有什么原因吗?这不是你编写的代码,那么测试它的意义何在? - shf301SmtpClient
,这样你的测试就不会依赖于SmtpClient
的行为。可以参考 https://dev59.com/1GIj5IYBdhLWcg3ws3Jf 中的示例。 - shf301