我正在尝试模拟包含在另一个对象中的对象的实例方法。
我有两个对象
class CreditCard(object):
def charge(self, amount):
if amount < 0:
raise Exception('Invalid amount')
print "charging %d" % amount
class Transaction(object):
def __init__(self, credit_card, amount):
self.amount = amount
self.credit_card = credit_card
self.status = 'PRISTINE'
def pay(self):
self.credit_card.charge(self.amount)
self.status = 'COMPLETE'
这是我要实现的目标的简化示例
class TestTransaction(TestCase):
def setUp(self):
cc = CreditCard()
t = Transaction(cc, 10)
def test_should_not_mark_transaction_as_complete_if_charge_failed(self):
with mock.patch('t.credit_card.charge') as mock_charge:
mock_charge.side_effect = Exception
with self.assertRaises(Exception):
t.pay()
self.assertEquaL(t.status, 'PRISTINE')
charge 中有很多逻辑,所以我试图通过模拟 charge 来隔离交易测试。
谢谢,python 2.7
请您参考如下方法:
因为你是模拟一个类的方法,你可以直接给它打补丁:
import mock
import unittest
from your_code import CreditCard, Transaction
class TestTransaction(unittest.TestCase):
def setUp(self):
self.cc = CreditCard()
self.t = Transaction(self.cc, 10)
@mock.patch('your_code.CreditCard.charge', side_effect=Exception)
def test_should_not_mark_transaction_as_complete_if_charge_failed(self, mock_charge):
with self.assertRaises(Exception):
self.t.pay()
self.assertEqual(self.t.status, 'PRISTINE')
请务必更新补丁中的模块路径,其中定义了您的类。
另外,由于几个错误(在测试用例中使用全局变量而不是实例属性),我更正了您的初始示例。
