【发布时间】:2014-10-21 03:35:42
【问题描述】:
我编写了一个测试 (NUnit) 来测试我的 Amazon SES 电子邮件发送功能,该功能应该在我的 Amazon SQS 队列中生成退回通知。我在一个新线程上循环轮询该队列 1 分钟,以等待并验证退回通知。
我想将时间增加到几分钟,以确保我不会错过它。但是响应可能会在几秒钟内出现,在这种情况下,我只想记录花费多长时间并完成测试,因为一旦验证收据,就没有必要继续等待了。
我怎样才能以干净的方式完成这个线程场景,我的意思是不污染 MethodInMainApp() 与测试代码。在主应用程序中,这不应该发生(它应该无限期地继续轮询),它应该只在测试早期停止。我可能应该从两个入口点传入 ThreadStart 函数,但这并不能回答我问的问题。
[Test]
public async void SendAndLogBounceEmailNotification()
{
Thread bouncesThread = Startup.MethodInMainApp();
bouncesThread.Start();
bool success = await _emailService.SendAsync(...);
Assert.AreEqual(success, true);
//Sleep this thread for 1 minute while the
//bouncesThread polls for bounce notifications
Thread.Sleep(60000);
}
public static Thread MethodInMainApp()
{
...
Thread bouncesThread = new Thread(() =>
{
while (true)
{
ReceiveMessageResponse receiveMessageResponse = sqsBouncesClient.ReceiveMessage(bouncesQueueRequest);
if(receiveMessageResponse.Messages.Count > 0)
{
ProcessQueuedBounce(receiveMessageResponse);
//done for test
}
}
});
bouncesThread.SetApartmentState(ApartmentState.STA);
return bouncesThread;
}
【问题讨论】:
标签: c# multithreading unit-testing nunit