重新导向控制台。在测试设置和拆卸 [英] Redirecting Console.Out within test Setup and Teardown

查看:191
本文介绍了重新导向控制台。在测试设置和拆卸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是抓取从单元测试中发送到Console.Out的输出?

This is a follow up from Grabbing the output sent to Console.Out from within a unit test? and the referenced article in the accepted answer by Mark Seemann.

我想使用Console.Out和Console.In来创建一个新的在测试时重定向流。类中的每个测试都需要使用重定向。

I would like to use Console.Out and Console.In to redirect the streams while testing. Every test in the class needs to use the redirects.

为了保持测试的清洁,我想在测试SetUp和TearDown。

In order to keep the tests clean I would like to do this in the 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()));
 }

然后我将在测试中使用'_sw.ToString

Then I would use '_sw.ToString()' within the tests to verify what was written to the stream.

使用设置或拆卸方法有什么主要缺点吗?
这类似于使用使用语句重定向吗?
Eg

Are there any major drawbacks of using setup or teardown methods for this? Would this similar to redirecting with a using statement? E.g.

using (StringWriter sw = new StringWriter())
{
    ...
}


推荐答案


< <>

Are there any major drawbacks of using setup or teardown methods for this?

是的,虽然它可能不可测量。

Yes, although it may not be measurable.

这里介绍设置 TearDown 方法,为每次测试创建新的一次性对象,但它们不会被丢弃。它们最终会超出范围,并在垃圾收集器运行时完成,但它可能以较少确定性的方式发生。理论上,它将使用更多的内存和处理器指令,而不是如果它们被确定性地处置,但正如Knuth教导我们40年前,我们应该测量而不是参与过早的优化。

The way Setup and TearDown method is described here, two new disposable objects are created for every test, but they are never disposed of. They'll eventually go out of scope and be finalised when the garbage collector runs, but it may happen in a less deterministic fashion. In theory, it'll use more memory and processor instructions than if they were deterministically disposed of, but as Knuth taught us 40 years ago, we should measure instead of engaging in premature optimisations.

我使用可变状态和隐式设置和拆卸的主要问题是,它不是线程-safe,所以如果你想同时运行你的单元测试,你不能。

My main problem with using mutable state and Implicit Setup and Teardown is that it's not thread-safe, so if you ever want to run your unit tests in parallel, you can't.

这篇关于重新导向控制台。在测试设置和拆卸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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