并行运行测试时使用 Console.SetOut 是否明智? [英] Is Console.SetOut wise to use when running tests in parallel?

查看:29
本文介绍了并行运行测试时使用 Console.SetOut 是否明智?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个控制台应用程序,按照此处所述重定向标准输出和标准输入:在测试设置和拆卸中重定向 Console.Out

I would like to test a console app, redirecting the std out and std in as described here: Redirecting Console.Out within test Setup and Teardown

这是代码:

private StringWriter _sw;
private StringReader _sr;
[SetUp]
public void SetUp()
{
    _sw = new StringWriter();
    Console.SetOut(_sw);
    _sr = new StringReader("100");
    Console.SetIn(_sr);
}

[TearDown]
public void TearDown()
{
    var standardOut = new StreamWriter(Console.OpenStandardOutput());
    standardOut.AutoFlush = true;
    Console.SetOut(standardOut);
    Console.SetIn(new StreamReader(Console.OpenStandardInput()));
 }

在每次测试中,我都会运行代码来读取和写入控制台.

Within each test, I will run code the reads and writes to the console.

从上面的代码可以看出,每个测试都以:

As can be seen in the code above, each test will begin with:

  _sw = new StringWriter();
  Console.SetOut(_sw);

如果多个测试并行运行,这些测试会相互冲突吗?

If multiple tests are run in parallel, will these tests conflict with each other?

从一个测试中调用 Console.SetOut 是否有可能在另一个测试中途改变重定向?这不会干扰测试吗?

Isn't it possible that calling Console.SetOut from one test, may change the redirection midway through another test? Wouldn't this disrupt the tests?

推荐答案

粗略地说,在每个线程的基础上重定向控制台只需要一个包装类.您将需要:

So roughly, to redirect the console on a per-thread basis requires little more than a wrapper class. You will need:

  1. 标记为 [ThreadLocal] 的静态字段,用于跟踪每个线程上当前测试的流.
  2. 一个 SetOut 方法,可能是静态的,很像全局(静态)Console.SetOut 方法,它允许每个测试在测试设置期间设置上述字段.
  3. 流虚拟方法的实现,它读取线程本地字段并将输出转发给它.
  4. 此包装器的一个实例,传递给 Console.SetOut.
  1. A static field, marked [ThreadLocal], to keep track of the stream for the current test on each thread.
  2. A SetOut method, probably static, much like the global (static) Console.SetOut method, that allows each test to set the above field during test setup.
  3. An implementation of the stream virtual methods, that reads the thread-local field and forwards output to it.
  4. An instance of this wrapper, passed to Console.SetOut.

这篇关于并行运行测试时使用 Console.SetOut 是否明智?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆