Last active
April 14, 2018 00:56
-
-
Save python012/3fca87520cf8067b424c7989ae340324 to your computer and use it in GitHub Desktop.
Try patch and mock functions in unit test
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
#!/usr/bin/env python3 | |
from unittest import TestCase | |
from unittest.mock import patch | |
from unittest import main | |
class Person(object): | |
def __init__(self, name): | |
self.name = name | |
def print_name(self): | |
print('My name is ' + self.name) | |
def print_parents(self): | |
mother = input("Enter mother's name: ") | |
father = input("Enter father's name: ") | |
print("{}'s parents are {} and {}.".format(self.name, mother, father)) | |
self.fake_func() | |
def fake_func(): | |
pass | |
class FuncTest(TestCase): | |
def test_print_parents(self): | |
john = Person('John') | |
with patch('builtins.input') as mocked_input: | |
mocked_input.side_effect = ('Jo', 'Lee') | |
with patch('builtins.print') as mocked_print: | |
with patch.object("Person.fake_func") as mocked_fake_func: | |
john.print_parents() | |
mocked_print.assert_called_with("John's parents are Jo and Lee.") | |
mocked_fake_func.assert_called_once() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rx:garrulous_py_practice reed$ python3 py_unittest_02.py
.
--------------------------------
Ran 1 test in 0.001s
OK