这是我尝试使用mock测试的代码的一般化示例。我得到了一个AttributeError。
这是__init __。py:
import logging
log = logging.getLogger(__name__)
class SomeError(Exception):
pass
class Stuff(object):
# stub
def method_a(self):
try:
stuff = self.method_b()
except SomeError, e:
log.error(e)
# show a user friendly error message
return 'no ponies'
return 'omg ponies'
def method_b(self):
# can raise SomeError
return ''
在tests.py中,我有类似的东西:
import mock
import unittest
from package.errors import SomeError
from mypackage import Stuff
some_error_mock = mock.Mock()
some_error_mock.side_effect = SomeError
class MyTest(unittest.TestCase):
@mock.patch.object('Stuff', 'method_b', some_error_mock)
def test_some_error(self):
# assert that method_a handles SomeError correctly
mystuff = Stuff()
a = mystuff.method_a()
self.assertTrue(a == 'no ponies')
运行测试时,mock会引发AttributeError说:“Stuff没有属性'method_b'”
我在这里做错了什么?
答案 0 :(得分:8)
装饰器的第一个参数应该是对象的类,你错误地使用了类的名字的字符串
@mock.patch.object('Stuff', 'method_b', some_error_mock)
应该成为
@mock.patch.object(Stuff, 'method_b', some_error_mock)
http://docs.python.org/dev/library/unittest.mock#patch-object