classA: defoutput(self): b = B() print(b.get_data())
# b.py classB: def__init__(self): pass
defget_data(self): return"B"
# test_a.py from pytest_mock import mocker
deftest_A_output(mocker): # Important!!这里要注意,你要patch掉的内容是在这个模块被导入的地方,而不是这个模块定义的地方 inst = mocker.patch("a.B") inst.get_data().return_value = "A" a = A() a.output() # A
classRemovalService(object): """A service for removing objects from the filesystem."""
defrm(filename): if os.path.isfile(filename): os.remove(filename) returnTrue returnFalse
# test_mymodule.py from mymodule import RemovalService
import mock import unittest
classRemovalServiceTestCase(unittest.TestCase): @mock.patch('mymodule.os.path') @mock.patch('mymodule.os') deftest_rm(self, mock_os, mock_path): # instantiate our service reference = RemovalService() # set up the mock mock_path.isfile.return_value = False ret = reference.rm("any path") assert ret == False # test that the remove call was NOT called. self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.") # make the file 'exist' mock_path.isfile.return_value = True ret = reference.rm("any path") mock_os.remove.assert_called_with("any path") assert ret == True