2014-09-04 126 views
0

我会尽量让自己清楚。我一直在练习单元测试,现在我正试图弄清楚如何测试下面的代码。带范围功能的单元测试

def main(): 

    for i in range(100): 
     print("Argh!") 

所以我只是想测试100次“唉!”的迭代。确保stdout通过测试。我甚至不知道如何开始单元测试。在这一个,虽然看起来很简单。

谢谢大家提前。

+0

python2还是python3? – mgilson 2014-09-04 22:04:31

回答

0

假设你使用python3,这成为容易使用模拟...

import unittest 
import mock # possibly "from unittest import mock" depending on version. 
import main_module 

class TestMain(unittest.TestCase): 
    def test_main(self): 
     with mock.patch.object(main_module, 'print') as mock_print: 
      mock_module.main() 
     expected_calls = [mock.call('Argh!') for _ in range(100)] 
     mock_print.assert_has_calls(expected_calls) 

if __name__ == '__main__': 
    unittest.main() 
+0

不错!你介意添加单元测试课的其余部分吗? – SalceCodec 2014-09-04 22:07:30