foo 类将外部库链接到一个属性,因此我可以使用 self.external_class.externalClassMethod。 但为了进行测试,我需要修补此方法调用,以便我可以继续测试该方法的其余部分。我已经尝试了 @patch 装饰器中的所有内容,但没有任何效果:(
import os
from unittest import TestCase
from unittest.mock import patch
class Foo(object):
def __init__(self):
self.os_handle = os
self.string = None
def path(self):
try:
print(self.os_handle.getNothing())
except Exception:
raise Exception
self.string = "circumvented the faulty os_handle method call"
class TestFoo(TestCase):
def testClass(self):
self.assertEqual(1,1)
def testLibraryCall(self):
with self.assertRaises(Exception) as cm:
foo = Foo()
foo.path()
self.assertEqual(cm.exception.__class__, Exception)
# @patch('os', 'getNothing', ...) # WHAT DO I PATCH?????
def testLibraryCallNoException(self):
foo = Foo()
foo.path()
self.assertEqual(foo.string, "circumvented the faulty os_handle method call")
将上面的代码保存在 my_class.py 中并运行上面的代码 $ python -m unittest my_class
尝试进行以下修改:
import os
from unittest import TestCase
from unittest.mock import patch
class Foo(object):
def __init__(self):
self.os_handle = os
self.string = None
def path(self):
try:
print(self.os_handle.getNothing())
except Exception:
raise Exception
self.string = "circumvented the faulty os_handle method call"
class TestFoo(TestCase):
def testClass(self):
self.assertEqual(1,1)
def testLibraryCall(self):
with self.assertRaises(Exception) as cm:
foo = Foo()
foo.path()
self.assertEqual(cm.exception.__class__, Exception)
def testLibraryCallNoException(self):
foo = Foo()
with patch.object(foo, "os_handle") as mock_os_handle:
foo.path()
self.assertEqual(foo.string, "circumvented the faulty os_handle method call")
我只修改了方法 testLibraryCallNoException():
patch.object()
代替 patch()
:这样属性 self.os_handle
就被模拟对象 mock_os_handle
替代了。这种替换的效果是,在您的生产代码中,指令 self.os_handle.getNothing()
没有按照您想要的方式执行任何操作(我在说明中省略了一些细节!)self.
添加到 assertEqual(foo.string, "circumvented the faulty os_handle method call")
以解决测试代码中的另一个错误。