从另一个 class 获取方法的输出并在 unittest 中测试它

Get output of method from another class and test it in unittest

我正在创建一个单元测试,我想测试一个方法的输出。我的代码有点大,所以我会用一个小例子。假设我的方法是这样的。

def foo():
     print "hello"

现在我去我的单元测试 class 我 运行 单元测试中的代码是这样的。

def test_code():
     firstClass.foo()

我想测试从控制台获得的输出。我看到有些人使用 subprocess 但我只能给出论据。所以我的问题是如何从控制台获取输出以在我的单元测试 class 中对其进行测试。

一个简单的解决方案是 remap stdout to a file 并处理文件 post 在单元测试中执行您的方法 class.

import sys
sys.stdout = open('result', 'w')

test_code()
# read 'result'

编辑: 或者,您可以使用 StringIO 模块操作文件流。

import StringIO
output = StringIO.StringIO()
sys.stdout = output

示例:

#!remap.py
import sys
import StringIO

backup_sys = sys.stdout # backup our standard out
output = StringIO.StringIO() # creates file stream for monitoring test result
sys.stdout = output
print 'test' # prints to our IO stream

sys.stdout = backup_sys # remap back to console
print output.getvalue() # prints the entire contents of the IO stream

输出

test

More details on the module can be found here.