如何在.NET中测试并发场景?

时间:2014-08-18 10:58:58

标签: c# .net testing asynchronous concurrency

我使用并发,但我不知道有什么好的方法来测试它。

我想知道是否有任何方法可以“强制”任务以特定顺序执行以模拟测试用例。

例如:

  1. 客户#1发出请求
  2. 服务器开始检索客户端#1
  3. 的数据
  4. 当服务器仍在响应客户端#1
  5. 时,客户端#2发出另一个请求
  6. 断言<<某事>>
  7. 我见过一些使用自定义TaskSchedulers的人。它有意义吗?

3 个答案:

答案 0 :(得分:1)

我在几次事件中也遇到过这个问题。最终我创建了一个帮助程序,可以启动一堆线程来执行并发操作。帮助程序提供同步原语和日志记录机制。这是来自单元测试的代码片段:

[Test]
public void TwoCodeBlocksInParallelTest()
{
    // This static method runs the provided Action delegates in parallel using threads
    CTestHelper.Run(
        c =>
            {
                Thread.Sleep(1000); // Here should be the code to provide something 
                CTestHelper.AddSequenceStep("Provide"); // We record a sequence step for the expectations after the test
                CTestHelper.SetEvent();
            },
        c =>
            {
                CTestHelper.WaitEvent(); // We wait until we can consume what is provided
                CTestHelper.AddSequenceStep("Consume"); // We record a sequence step for the expectations after the test
            },
        TimeSpan.FromSeconds(10)); // This is a timeout parameter, if the threads are deadlocked or take too long, the threads are terminated and a timeout exception is thrown 

    // After Run() completes we can analyze if the recorded sequence steps are in the correct order
    Expect(CTestHelper.GetSequence(), Is.EqualTo(new[] { "Provide", "Consume" }));
}

它可用于测试客户端/服务器或组件中的同步,或者只是运行超时的线程。我将在接下来的几周内继续改进这一点。这是项目页面: Concurrency Testing Helper

答案 1 :(得分:0)

使用任务模拟这不应该太难:

private async Task DoSomeAsyncOperation()
{
    // This is just to simulate some work,
    // replace this with a usefull call to the server
    await Task.Delay(3000);
}

现在,让我们消费它:

public async Task TestServerLoad()
{
   var firstTaskCall = DoSomeAsyncOperation();

   await Task.Delay(1000); // Lets assume it takes about a second to execute work agains't the server
   var secondCall = DoSomeAsyncOperation();

   await Task.WhenAll(firstTaskCall, secondCall); // Wait till both complete
}

答案 2 :(得分:0)

这是并发中基本的生产者 - 消费者问题。如果你想测试那种情况,只需将一个Thread.Sleep(100)放到服务器上哪个部分响应消费者。这样,您的服务器在发送响应之前会有延迟。您只需在循环中创建新线程即可调用服务请求。