【问题标题】:How to mock a call to a method of a related model?如何模拟对相关模型方法的调用?
【发布时间】:2015-10-26 08:53:03
【问题描述】:

我有以下 django 模型

class Charge(models.Model):
    total = models.PositiveIntegerField()

    def execute():
        # make some external calls
        return invoice_url

class Transaction(models.Model):
    product = models.ForeignKey(Product)
    charge = models.ForeignKey(Charge)

    def do_charge():
        self.charge = Charge.objects.create(total=self.product.price)
        url = self.charge.execute()
        return url

我正在尝试通过模拟对execute 的调用来测试do_charge。 问题是对象是在do_charge 中创建的。

类似的东西(这显然不是为了说明)

@mock.patch('Charge.execute')
def test_should_return_url(self, mock):
    mock.side_effect = 'www.foo.testing/invoice' 
    t = Transaction.objects.create(product=p1)
    invoice_url = t.do_charge()
    self.assertIsEqual(invoice_url, 'www.foo.testing/invoice')

可以模拟Charge.execute吗?

python 3.4,django 1.8。

【问题讨论】:

  • 执行不是静态方法,是吗?
  • 不,是实例方法。

标签: django unit-testing mocking


【解决方案1】:

我尝试了下一个代码来测试模拟行为,似乎模拟 Charge.execute 应该可以工作。

>>> class A(object):
...     def foo(self):
...         return 'a'

>>> @mock.patch('__main__.A.foo', return_value='12')
... def bar(mockfoo):
...     a = A()
...     return a.foo()
... 
>>> bar()
'12'

在这里,我模拟了一个类的方法,创建了一个类实例并调用了对象的方法,它使用了模拟版本。所以我认为在你的测试中会使用模拟 Charge.execute 。我认为您面临的问题可能与您要模拟的课程的正确路径有关。

【讨论】:

  • 是的,问题是当将模拟的charge 分配给transaction.charge 时,它会抛出无效类型(这是有道理的)。虽然可能只模拟模型实例方法。
猜你喜欢
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多