我正在測試一個應用程序。 A [TearDown]
方法包含另一種發送請求服務器的方法。這個很慢。同時一臺服務器不能同時處理3個以上的請求。NUnit和測試在不同的線程
所以我決定使用信號量。
[TestFixture]
public class TestBase
{
private const int MaxThreadsCount = 3;
private readonly Semaphore _semaphore = new Semaphore(MaxThreadsCount, MaxThreadsCount);
[SetUp]
public virtual void Setup()
{
}
[TearDown]
public void CleanUp()
{
//...some code
new Thread(_ => SendRequestAsync("url/of/a/server", parameters)).Start();
}
private void SendRequestAsync(string url, NameValueCollection parameters)
{
_semaphore.WaitOne();
string result = MyServerHelper.SendRequest(url, parameters);
Assert.That(string.IsNullOrEmpty(result), Is.False, "SendRequest returned false");
}
[Test]
public void Test01()
{
Assert.AreEqual(1, 1);
}
[Test]
public void Test02()
{
Assert.AreEqual(1, 1);
}
[Test]
public void Test03()
{
Assert.AreEqual(1, 1);
}
//...........................
[Test]
public void TestN()
{
Assert.AreEqual(1, 1);
}
}
但是,它似乎不能正常工作。現在在服務器上的日誌文件中沒有記錄,這意味着服務器不會收到任何請求。
1)我做錯了什麼?
2)如何初始化一個信號:
private readonly Semaphore _semaphore = new Semaphore(MaxThreadsCount, MaxThreadsCount);
或
private readonly Semaphore _semaphore = new Semaphore(0, MaxThreadsCount);
<<是否有一個原因,你需要在一個單獨的線程運行它? >>因爲'MyServerHelper.SendRequest'很慢,並阻止所有其他測試,直到它完成。 – Alexandre
@AlexMaslakov可能使用像AutoFac或引用計數這樣的IoC容器來管理此內容,以便在需要它的測試之間共享此內容。也許可以考慮同時運行測試(見http://www.nunit.org/index.php?p=pnunit&r=2.5)。 – akton
<<測試運行程序可能在線程結束(甚至啓動)之前結束測試過程>>是否有任何方法讓測試運行程序等待直到最後一個線程結束? – Alexandre