Mocking print() in Unit Tests
It can be difficult to write unit tests for methods like
print() that don’t return anything but have a side-effect of writing to the terminal. You want to ensure that what you expected to print to the terminal actually got printed to the terminal. The
unittest.mock library can help you test functions that have calls to
def greet(name): print('Hello ', name) from unittest.mock import patch @patch('builtins.print') def test_greet(mock_print): # The actual test greet('John') mock_print.assert_called_with('Hello ', 'John') greet('Eric') mock_print.assert_called_with('Hello ', 'Eric') # Showing what is in mock import sys sys.stdout.write(str( mock_print.call_args ) + '\n') sys.stdout.write(str( mock_print.call_args_list ) + '\n')
Become a Member to join the conversation.