Last active
June 7, 2019 07:54
-
-
Save konradhalas/788af3dceb75417fc1e0fde1b207a4a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from unittest import mock | |
# Approach #1 - hidden dependency | |
def func_1(): | |
pass | |
def func_2(): | |
# You have to read `func_2` code to figure out that it uses `func_1` 👎 | |
result = func_1() | |
... | |
def test_func_2(): | |
# ... and then you have to "patch" it if you want to "unit" test it 😪 | |
with mock.patch("func_1") as func_1_mock: | |
func_1_mock.return_value = ... | |
func_2() | |
assert ... | |
# Approach #2 - explicit dependency | |
class ClassA: | |
def method_1(self): | |
pass | |
class ClassB: | |
# You can not create `ClassB` instance without providing `ClassA` object 👍 | |
def __init__(self, class_a: ClassA) -> None: | |
self.class_a = class_a | |
def method_2(self): | |
result = self.class_a.method_1() | |
... | |
def test_method_1(): | |
# ... and now test looks beautifull 🎉 | |
class_a_mock = mock.Mock(spec=ClassA) | |
class_a_mock.method_1.return_value = ... | |
class_b = ClassB(class_a=class_a_mock) | |
class_b.method_2() | |
assert ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment