rogervinas / tests-everywhere
🤠 Tests, Tests Everywhere!
Python testing this simple Hello World with unittest
Show me the code
Implementation
- Create
HelloMessage
class in hello_message.py:
class HelloMessage:
def __init__(self):
self.text = "Hello World!"
- Create
HelloConsole
class in hello_console.py:
from builtins import print as __print__
class HelloConsole:
def print(self, text):
__print__(text)
Note that we have to import print
system function as __print__
to avoid conflict with HelloConsole
own print
method.
- Create
HelloApp
class in hello_app.py:
class HelloApp:
def __init__(self, message, console):
self.message = message
self.console = console
def print_hello(self):
self.console.print(self.message.text)
- Create main function in __main__.py that wraps it all together:
message = HelloMessage()
console = HelloConsole()
app = HelloApp(message, console)
app.print_hello()
Test
Following unittest > Basic example and unittest.mock > Quick Guide guides ...
- Test
HelloMessage
in test_hello_message.py:
class HelloMessageTest(unittest.TestCase):
def test_should_return_hello_world(self):
message = HelloMessage()
self.assertEqual(message.text, "Hello World!")
- Test
HelloApp
in test_hello_app.py:
class HelloAppTest(unittest.TestCase):
def test_should_print_hello_message(self):
message_text = "Hello Test!"
# 2.1 Create a mock of HelloMessage
message = MagicMock()
# 2.2 Return "Hello Test!" whenever text is called
message.text = message_text
# 2.3 Create a mock of HelloConsole
console = MagicMock()
# 2.4 Mock print method
console.print = MagicMock()
# 2.5 Create a HelloApp, the one we want to test, passing the mocks
app = HelloApp(message, console)
# 2.6 Execute the method we want to test
app.print_hello()
# 2.7 Verify HelloConsole mock print() method
# has been called once with "Hello Test!"
console.print.assert_called_once_with(message_text)
- Test output should look like:
test_should_print_hello_message (test.test_hello_app.HelloAppTest.test_should_print_hello_message) ... ok
test_should_return_hello_world (test.test_hello_message.HelloMessageTest.test_should_return_hello_world) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
Happy Testing! 💙
Top comments (0)