0

次の方法でコンストラクターを定義しました。

def __init__(self):
    //set some properties
    ...
    self.helperMethod()

def helperMethod(self):
    //Do some operation

ヘルパー メソッドを単体テストしたいのですが、単体テストを実行するためのオブジェクトを作成するには、__init__メソッドを実行する必要があります。ただし、これを行うとヘルパー メソッドが呼び出されますが、これは望ましくありません。これは、テストする必要があるメソッドだからです。

__init__メソッドをモックアウトしようとしましたが、 __init__ should return None and not MagicMock.

以下の方法でヘルパーメソッドのモックアウトも試みましたが、モックしたメソッドを手動で復元する方法が見つかりませんでした。MagicMock.reset_mock() はこれを行いません。

SomeClass.helperMethod = MagicMock()
x = SomeClass()
[Need someway to undo the mock of helperMethod here]

ヘルパーメソッドを単体テストするための最良の方法は何ですか?

4

1 に答える 1

0

の元の値をキャプチャしようとしましたhelperMethodか?

original_helperMethod = SomeClass.helperMethod
SomeClass.helperMethod = MagicMock()
x = SomeClass()
SomeClass.helperMethod = original_helperMethod

ライブラリのpatchデコレータを使用することもできますmock

from mock import patch

class SomeClass():

    def __init__(self):
        self.helperMethod()

    def helperMethod(self):
        assert False, "Should not be called!"

x = SomeClass() # Will assert 
with patch('__main__.SomeClass.helperMethod') as mockHelpMethod:
    x = SomeClass() # Does not assert
于 2013-09-17T20:05:01.207 に答える