2015-09-03 60 views
0

我有一個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' 

我期望看到 「ABC123」 爲donation.charge_id,而是我看到了MagicMock的Unicode表示。我究竟做錯了什麼?

回答

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相匹配我的期望。儘管如此,我仍然想知道我在前面的代碼中做了什麼錯誤。