2017-03-16 7 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あなたの例では:あなたがpytestを使用している場合、あなたはまた、フィクスチャを作成して、自動的にautouseでそれを使用することができることを

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 

注意してください。ここの例を確認してください:http://pythontesting.net/framework/pytest/pytest-fixtures-nuts-bolts/#autouse

関連する問題