MSTest:断言线程执行

发布于 2024-10-03 23:30:40 字数 171 浏览 1 评论 0原文

在我的测试中,我想启动 2 个线程并在每个线程执行结束时检查一些断言条件。

在这种情况下,实施测试的最佳实践是什么?我知道在两个线程启动后我需要等待它们完成...是否有任何开箱即用的解决方案或者我需要“手动”执行此操作(例如,在测试结束时我可以等待 2每个事件都由线程之一设置)。

请指教,谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

背叛残局 2024-10-10 23:30:40

如果您使用 .Net 4,您可以使用任务来完成在不同线程上运行测试。以下将:

  • 在两个不同的线程上运行测试代码。
  • 等待测试运行。
  • 测试运行之后断言条件。

示例:

    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

在线程测试运行后断言条件非常重要,因为断言失败应该发生在运行测试的线程上,而不是在生成的线程上。生成的线程(即非测试线程)上的异常将被视为未处理的异常,而不是“测试”断言异常。

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.

最好是你 2024-10-10 23:30:40

您应该小心运行多线程单元测试。这可能会降低它们的可靠性。它更多的是用于集成测试。但是,如果您确实愿意,可以在两个线程上调用 Join

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

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

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

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();
终遇你 2024-10-10 23:30:40

为什么不使用两个线程的 Join 方法?

Why not using Join method of your two threads?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文