Skip to content

Instantly share code, notes, and snippets.

@MGough
Last active November 17, 2019 22:15
Show Gist options
  • Save MGough/24e2670a9656c8c19811965ed0c9f24f to your computer and use it in GitHub Desktop.
Save MGough/24e2670a9656c8c19811965ed0c9f24f to your computer and use it in GitHub Desktop.
An example of *fragile* unit tests due to bad mocks.
from unittest.mock import patch, Mock
from pytest import fixture
from src.example import SomeObjectToTest
class TestSomeObjectToTest:
@fixture
def expected_result(self):
return 400
def test_do_something(self, expected_result):
object_under_test = SomeObjectToTest()
mocked_calculator = Mock()
mocked_calculator.add.return_value = expected_result
result = object_under_test.do_something(mocked_calculator)
assert result == expected_result
mocked_calculator.add.assert_called_once_with(5, 10)
@patch("src.example.SomeClassOutOfOurControl")
def test_do_something_else(self, mocked_class, expected_result):
mocked_class.return_value.add.return_value = expected_result
object_under_test = SomeObjectToTest()
result = object_under_test.do_something_else()
assert result == expected_result
object_under_test.calculator.add.assert_called_once_with(5, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment