Python – In python, how to do unit test on a function without return value

pythonunit testing

I am a pythoner. At these days I am driving myself to do a more complete unit test on some core module in my project.
Since we always do unit test with methods 'assertEqual', 'assertTrue' and so on, these methods all require a return value from the function being tested, I am wondering how to do a plain unit test on some function without a return value.

I would like to show a tiny example here, how to test function def foo(self, msg) in HelloTest?

class HelloTest(object):
    def foo(self, msg):
        MSG = msg.upper()
        self.bar(MSG)

    def bar(self, MSG):
        print MSG

Best Answer

As another answer mentioned, you can use the Python mock library to make assertions about calls to functions/methods

from mock import patch
from my_module import HelloTest
import unittest

class TestFoo(unittest.TestCase):

    @patch('hello.HelloTest.bar')
    def test_foo_case(self, mock_bar):

        ht = HelloTest()

        ht.foo("some string")
        self.assertTrue(mock_bar.called)
        self.assertEqual(mock_bar.call_args[0][0], "SOME STRING")

This patches out the bar method on HelloTest and replaces it with a mock object that records calls against it.

Mocking is a bit of a rabbit hole. Only do it when you absolutely have to because it does make your tests brittle. You'll never notice an API change for a mocked object for instance.