<p>我不太明白为什么每个人都想检查foo叫bar</p>
<p>Foo有一些功能,这个功能需要测试。如果foo正在使用bar来做这件事,我不应该担心</p>
<p>期望的结果是,在调用<code>foo(msg)</code>之后,<code>msg.upper()</code>被发送到stdout</p>
<p>您可以<a href="https://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer">redirect stdout to a string buffer</a>并检查此字符串缓冲区的内容是否与您期望的内容匹配</p>
<p>例如:</p>
<pre><code>import sys
import unittest
from io import TextIOWrapper, BytesIO
class TestScript(unittest.TestCase):
def setUp(self):
self._old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)
def _output(self):
self._stdout.seek(0)
return self._stdout.read()
def test_foo(self):
hello_test = HelloTest()
hello_test.foo("blub")
self.assertEqual(self._output(), "BLUB")
def tearDown(self):
sys.stdout = self._old_stdout
self._stdout.close()
</code></pre>
<p>您也可以对stdin这样做(并写入stdin以模拟某些输入),如果需要做任何特殊的事情,您可以将TestIOWrapper子类化,比如允许非unicode文本发送到<code>sys.stdout</code>,而不使用<code>sys.stdout.buffer</code>(Python2与Python3)。
在<a href="https://stackoverflow.com/a/19345047/1904815">this SO answer</a>中有一个例子。
当您(仍然)仅使用Python2时,使用<code>StringIO</code>可能比使用io模块更好</p>