Python: Write unittest for console print

后端 未结 4 2216
无人及你
无人及你 2020-12-02 11:03

Function foo prints to console. I want to test the console print. How can I achieve this in python?

Need to test this function, has NO return statement

4条回答
  •  盖世英雄少女心
    2020-12-02 11:44

    You can also use the mock package as shown below, which is an example from https://realpython.com/lessons/mocking-print-unit-tests.

    from mock import patch
    
    def greet(name):
        print('Hello ', name)
    
    @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')
    

提交回复
热议问题