Budda
Budda

Reputation: 18353

MSTest: assert threads execution

In my test I want to launch 2 threads and check some assert conditions in the end of each thread execution.

What is best practice to implement for tests in this case? I understand that after both threads launching I need to wait while they finish... Is there any out-of-the box solutions or I need to do that "manually" (for example, in the end of test I could wait for 2 events each of them to be set-up by one of threads).

Please advise, thanks!

Upvotes: 2

Views: 730

Answers (3)

Tim Lloyd
Tim Lloyd

Reputation: 38464

If you are using .Net 4 you can use tasks to accomplish running tests on different threads. The following will:

  • Run test code on two different threads.
  • Wait for the tests to run.
  • Assert conditions after the tests have run.

Example:

    Action test1 = () => { /* Test code 1 */};
    Action test2 = () => { /* Test code 2 */};

    Task task2 = null;
    Task task1 = new Task(() =>
    {
        task2 = new Task(test2);
        task2.Start();

        test1();
    });

    task1.Start();
    task1.Wait();
    task2.Wait();

    //Assert test 1
    //Assert test 2

It is important to assert conditions after the threaded tests have run as assertion failures should occur on the thread running the test and not on spawned threads. Exceptions on spawned threads (i.e. non-test threads) will be seen as unhandled exceptions and not "test" assertion exceptions.

Upvotes: 2

Steven
Steven

Reputation: 172786

You should be careful running multi-threaded unit tests. This might make them less reliable. It's more something for integration tests. However, if you really want to, you can call Join on both threads:

Thread t1 = ...;
Thread t2 = ...;

t1.Start();
t2.Start();

// Wait for threads to finish:
t1.Join();
t2.Join();

Upvotes: 1

alpha-mouse
alpha-mouse

Reputation: 5003

Why not using Join method of your two threads?

Upvotes: 1

Related Questions