source: xUnit Patterns - Test Double
Apollo 13 - Flight Simulator
Apollo 13 - Flight Simulator
replace a component on which the SUT depends with a "test-specific equivalent."
source: xUnit Patterns - Test Double
非出口點的依賴關係。
它們並不代表該工作單元最終行為的需求。
它們只是在此處為工作單元提供特定於測試的專用資料或行為。
例如:
請注意,這些是先前的系統運作的結果,是被動資料,向內流入工作單元。
傳入依賴
一個 Stub 範例
def test_room601_operations_true(operation_data: List[lib.Operation], mocker: pytest_mock.MockFixture): mocker.patch('lib.get_operations_from_db', autospec=True, return_value=operation_data) room = '601' operations = lib.all_operations(date(2021, 7, 13), room) assert all(op.room == room for op in operations)
代表我們工作單元出口的依賴。
例如:
請注意,這些都是動詞:“調用”,“發送”和“通知”
傳出依賴
互動方式測試
def test_electric_guitars(guitar_data: List[lib.Guitar], mocker: pytest_mock.MockFixture): # uncomment the following 2 line to mock the external dependency mocker.patch('lib.get_guitars_from_db', autospec=True, return_value=guitar_data) mock_log = mocker.patch('lib.log', autospec=True) style = 'electric' guitars = lib.all_guitars(style) # sweet little generator expression assert all(g.style == style for g in guitars) # uncomment the following line to test the external dependency behave as design mock_log.assert_called_once_with(f"Guitars for {style}")
pip install pytest-cov
pytest tests.py --cov=. pytest tests.py --cov=. --cov-report=html pytest tests.py --cov=. --cov-report=xml
思考:覆蓋率是否愈多愈好?
def foo(x: int, y: int) -> int: z = 0 if (x > 0) and (y > 0): z = x return z
def foo(x: int, y: int) -> int: z = 0 if (x > 0) and (y > 0): z = x return z
def foo(x: int, y: int) -> int: z = 0 if (x > 0) and (y > 0): z = x return z