【问题标题】:python/django unittest function overridepython/django unittest 函数覆盖
【发布时间】:2010-06-24 22:19:12
【问题描述】:

我有一个耗时的方法,其中包含非预定义的迭代次数,我需要测试:

def testmethod():
    objects = get_objects()
    for objects in objects:
        # Time-consuming iterations
        do_something(object)

一次迭代足以对我进行测试。仅通过一次迭代测试此方法的最佳做法是什么?

【问题讨论】:

    标签: python django unit-testing


    【解决方案1】:

    也许把你的方法变成

    def my_method(self, objs=None):
        if objs is None:
            objs = get_objects()
        for obj in objs:
            do_something(obj)
    

    然后在您的测试中,您可以使用自定义 objs 参数调用它。

    【讨论】:

      【解决方案2】:

      更新:

      我误读了原始问题,所以我将在不更改源代码的情况下解决问题:

      Lambda 出您的调用以获取对象以返回单个对象。例如:

      from your_module import get_objects
      
      def test_testmethdod(self):
          original_get_objects = get_objects
          one_object = YourObject()
          get_objects = lambda : [one_object,]
      
          # ...
          # your tests here
          # ...
      
          # Reset the original function, so it doesn't mess up other tests
          get_objects = original_get_objects
      

      【讨论】:

      • 但在您的示例中,将始终执行 break,不仅在测试用例中使用此方法时。
      • 对不起,我误读了您的原始问题。我已经用不会强迫您更改来源的解决方案更新了我的答案。
      • 好的,我了解你的解决方案,我也在其他测试中使用它,但在这种情况下,我将使用 Alex 的技术,无论如何都要投票
      猜你喜欢
      • 2017-09-30
      • 2020-09-17
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      相关资源
      最近更新 更多