2017-03-16 62 views
2

正試圖解決Python中的在線編碼問題,並且提交所需的I/O很簡單input()print()。由於我很懶,不想用方法參數替換I/O以運行單元測試,我將如何創建一個單元測試,以允許我將預設字符串替換爲輸入?例如:Python 3中單元測試的預設輸入

class Test(TestCase): 
    __init__(self): 
     self.input = *arbitrary input* 
    def test(self): 
     c = Class_Being_Tested() 
     c.main() 
     ...make self.input the required input for c.main() 
     ...test output of c.main() 

回答

2

您可以使用mock.patch()將調用修補到任何對象。在這種情況下,這意味着修補input()。您可以在文檔閱讀更多關於它:https://docs.python.org/dev/library/unittest.mock.html在您的例子:

import mock 
class Test(TestCase): 
    @mock.patch('builtin.input') 
    def test_input(self, input_mock): 
     input_mock.return_value = 'arbitrary string' 
     c = Class_Being_Tested() 
     c.main() 
     assert c.print_method.called_with('arbitrary string') #test that the method using the return value of input is being called with the proper argument 

請注意,如果你正在使用pytest你還可以創建一個固定裝置和自動autouse使用它。在此處查看示例:http://pythontesting.net/framework/pytest/pytest-fixtures-nuts-bolts/#autouse