模拟修补函数返回的对象有困难

时间:2015-09-03 02:58:54

标签: django unit-testing python-mock

我在Django表单类上有一个实例方法,如果成功,它会从支付服务返回一个Python对象。

该对象具有id属性,然后我将其保存在Django模型实例上。

我很难让模拟对象正确返回其.id属性。

# tests.py

class DonationFunctionalTest(TestCase):

    def test_foo(self):

        with mock.patch('donations.views.CreditCardForm') as MockCCForm:
            MockCCForm.charge_customer.return_value = Mock(id='abc123')

            # The test makes a post request to the view here.

            # The view being tested calls:

            # charge = credit_card_form.charge_customer()
            # donation.charge_id = charge.id
            # donation.save()

然而:

print donation.charge_id

# returns
u"<MagicMock name='CreditCardForm().charge_customer().id'

我希望看到&#34; abc123&#34;对于donation.charge_id,但我看到了MagicMock的unicode表示。我做错了什么?

1 个答案:

答案 0 :(得分:1)

通过稍微不同的修补来实现它:

@mock.patch('donations.views.CreditCardForm.create_card')
@mock.patch('donations.views.CreditCardForm.charge_customer')
def test_foo(self, mock_charge_customer, mock_create_card):

    mock_create_card.return_value = True
    mock_charge_customer.return_value = MagicMock(id='abc123')

    # remainder of code

现在id符合我的预期。我仍然想知道我在前面的代码中做错了什么。