2010-06-24 19 views
0

我與非預定數量內它的迭代耗時的方法,我需要測試:蟒/ django的單元測試功能倍率

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

一次迭代是足以測試我。僅使用一次迭代測試此方法的最佳做法是什麼?

回答

2

也許把你方法引入

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

然後在您的測試,你可以用自定義的OBJ參數調用它。

+0

謝謝。我會試試這個 – dragoon 2010-06-24 22:25:24

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 
+0

但是在你的例子中,break不僅會在測試用例中使用這個方法。 – dragoon 2010-06-24 22:59:34

+0

對不起,我誤解了你的原始問題。我已經用不會強迫你改變源的解決方案更新了我的答案。 – sdolan 2010-06-24 23:25:56

+0

好吧,我瞭解你的解決方案,我也在其他測試中使用它,但在這種情況下,我會使用亞歷克斯的技術,無論如何投票 – dragoon 2010-06-24 23:34:27