2

I have TestMethod and I need to run it N-times in different N-threads. I want to do this for testing behavior of my WebMethod - I can get several requests from different threads in one moment.

How I can run TestMethod repeatedly in several Threads in Unit Test C#? How I can set amount of calls of my TestMethod?

Yuliia Ashomok
  • 8,336
  • 2
  • 60
  • 69
  • 1
    May be moving you code to a "normal" method and doing the threading in the test method will work. –  Sep 16 '14 at 14:18

2 Answers2

3

The easiest way IMHO is this:

Create a testmethod that runs the test one time.

Create a LoadTest Unit Test and assign your testmethod as it's only test.

Set the number of tests you want to run concurrently.

Chuck Buford
  • 321
  • 1
  • 9
3

You can do it by creating N tasks, starting all of them and then waiting for them to finish. You can use Assert methods inside the tasks, when they fail an AssertionFailedException will be thrown and you can catch that on the parent thread easily when using async/await. I believe MsTest supports the async keyword for test methods from Visual Studio 2012 (or 2013). Something like this:

// 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!");
    }
}

If you have the Premium or Ultimate version of Visual Studio then you can make this easier by creating load tests:

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

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Bedford
  • 1,136
  • 2
  • 12
  • 36
  • 1
    “async void” unit tests can't be recognized as unit test by VS. This problem was described here http://stackoverflow.com/questions/19317135/why-cant-async-void-unit-tests-be-recognized – Yuliia Ashomok Sep 17 '14 at 10:30