概要
- 単体テストを書く際に、Privateメソッドの呼び出しに苦労したので方法を書き下しておく。
ケース1(通常呼び出し)
テスト対象ファイル
function.py
class Service:
def __private(self, name):
return name
テストファイル
test.py
from function import Service
def test_private():
name = "Smith"
s = Service()
r = s._Service__private(name)
assert r == "Smith"
[クラスのインスタンス]._[クラス名]__[Privateメソッド名]
ケース2(Mockする場合)
テスト対象ファイル
function.py
class Service:
def __private(self):
return 1
def no_private(self):
return self.__private()
テストファイル
test.py
from function import Service
from unittest.mock import patch
def test_mock_private(method):
s = Service()
with patch.object(s, '_Service__private', return_value=3) as method:
s.no_private()
method.assert_called_once_with()
もしくは
test.py
from function import Service
from unittest.mock import patch
@patch.object(Service, "_Service__private", return_value=3)
def test_mock_private(method):
s = Service()
s.no_private()
method.assert_called_once_with()
ケース3(複数のメソッドをMockする場合)
テスト対象ファイル
function.py
class Service:
def __private_1(self):
return 1
def __private_2(self):
return 2
def no_private(self):
self.__private_1()
self.__private_2()
test.py
from function import Service
from unittest.mock import patch
@patch.object(Service, "_Service__private_1", return_value=3)
@patch.object(Service, "_Service__private_2", return_value=3)
def test_mock_private(method1, method2):
s = Service()
s.no_private()
method.assert_called_once_with()
ケース4(テーブル定義をモックする場合)
example.py
def test_add_new_table():
td = Mock(TableDefinition)
td.table_name = "table_name"
patch.object(LocalDbService, "_Service__get_all_table_definitions", return_value=td)