【问题标题】:How to run TestMethod repeatedly in several Threads in Unit Test C#如何在单元测试C#的多个线程中重复运行TestMethod
【发布时间】:2014-11-10 08:09:27
【问题描述】:

我有 TestMethod,我需要在不同的 N 线程中运行它 N 次。我想这样做是为了测试我的 WebMethod 的行为——我可以在一瞬间从不同的线程中获得多个请求。

如何在单元测试 C# 的多个线程中重复运行 TestMethod?如何设置 TestMethod 的调用次数?

【问题讨论】:

  • 可能会将您的代码移动到“正常”方法,并且在测试方法中进行线程处理将起作用。

标签: c# multithreading unit-testing


【解决方案1】:

您可以通过创建 N 个任务、启动所有任务然后等待它们完成来实现。您可以在任务中使用 Assert 方法,当它们失败时将抛出 AssertionFailedException 并且您可以在使用 async/await 时轻松地在父线程上捕获它。我相信 MsTest 支持 Visual Studio 2012(或 2013)中测试方法的 async 关键字。像这样的:

// no TestMethod attribute here
public Task TestMyWebMethodAsync() 
{
    return Task.Run(() => 
      {
        // add testing code here
        
        Assert.AreEqual(expectedValue, actualValue);
      });                
}

[TestMethod]
public async void ParallelTest() 
{
    try {
        const int TaskCount = 5;
        var tasks = new Task[TaskCount];
        for (int i = 0; i < TaskCount; i++) 
        {
            tasks[i] = TestMyWebMethodAsync();
        }
        
        await Task.WhenAll(tasks);
        
    // handle or rethrow the exceptions
    } catch (AssertionFailedException exc) {
        Assert.Fail("Failed!");
    } catch (Exception genericExc) {
        Assert.Fail("Exception!");
    }
}

如果您拥有 Visual Studio 的 Premium 或 Ultimate 版本,则可以通过创建负载测试来简化此操作:

https://docs.microsoft.com/en-us/previous-versions/azure/devops/test/load-test/run-performance-tests-app-before-release

【讨论】:

【解决方案2】:

恕我直言,最简单的方法是:

创建一个运行一次测试的测试方法。

创建一个 LoadTest 单元测试并指定您的测试方法,因为它只是测试。

设置要同时运行的测试数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    相关资源
    最近更新 更多