0
2

More than 1 year has passed since last update.

PytestでPrivateメソッドを扱う時の備忘録

Last updated at Posted at 2023-02-02

概要

  • 単体テストを書く際に、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)
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2