Python 自帶的 unittest 庫能夠用來寫單元測試。python
測試輸入輸出的解決方法是:
將標準輸入輸出定向到一個StringIO類(python3是 io.StringIO)。單元測試
import unittest import io import sys def stub_stdin(testcase_inst, inputs): stdin = sys.stdin def cleanup(): sys.stdin = stdin testcase_inst.addCleanup(cleanup) sys.stdin = io.StringIO(inputs) def stub_stdout(testcase_inst): stderr = sys.stderr stdout = sys.stdout def cleanup(): sys.stderr = stderr sys.stdout = stdout testcase_inst.addCleanup(cleanup) sys.stderr = io.StringIO() sys.stdout = io.StringIO() def fun(): x = int(input()) print(x+5) class UnitTest(unittest.TestCase): def test_fun(self): stub_stdin(self, '2\n4\n') # 依次輸入2,4 stub_stdout(self) fun() self.assertEqual(str(sys.stdout.getvalue()), '7\n') stub_stdout(self) # 重置輸出 fun() self.assertEqual(str(sys.stdout.getvalue()), '9\n') if __name__ == '__main__': unittest.main()