2013-01-16 29 views
4

我有一個非常簡單的設置,使用unittest,我得到一個我不明白的錯誤。Python unittest - ValueError:沒有這樣的測試方法在<class'mytestcase.MyTestCase'>:runTest

# mytestcase.py 
import unittest 

class MyTestCase(unittest.TestCase): 
    def test_one(self): 
     self.assertTrue(True) 
    def test_two(self): 
     self.assertTrue(False) 


def initialize(): 
    return MyTestCase() 

if __name__ == '__main__': 
    unittest.main() 

如果我執行上述文件,我得到以下的結果,這是我期待和理解:

> python mytestcase.py 
.F 
====================================================================== 
FAIL: test_two (__main__.MyTestCase) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "mytestcase.py", line 7, in test_two 
    self.assertTrue(False) 
AssertionError: False is not true 

---------------------------------------------------------------------- 
Ran 2 tests in 0.000s 

FAILED (failures=1) 

但我想運行這些測試的另一種方式,從my_test_manager.py

# my_test_manager.py 
import mytestcase 

test_case = mytestcase.initialize() 
test_suite = unittest.TestLoader().loadTestsFromTestCase(test_case) 
test_suite_result = unittest.TestResult() 
test_suite.run(test_suite_result) 
for err in test_suite_result.errors: 
    print err 
for fail in test_suite_result.failures: 
    print fail 

但是,如果我嘗試運行此文件,它崩潰如下:

> python my_test_manager.py 
Traceback (most recent call last): 
    File "my_test_manager.py", line 3, in <module> 
    test_case = mytestcase.initialize() 
    File "/Users/Jon/dev/test-tools/practice/mytestcase.py", line 11, in initialize 
    return MyTestCase() 
    File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 191, in __init__ 
    (self.__class__, methodName)) 
ValueError: no such test method in <class 'mytestcase.MyTestCase'>: runTest 
+0

可能重複的[ValueError異常:在沒有這樣的測試方法<類 'myapp.tests.SessionTestCase'>:的runTest](http://stackoverflow.com/questions/2090479/valueerror -no-such-test-method-in-class-myapp-tests-sessiontestcase-runtes) – brandizzi

+0

查看[this](https://stackoverflow.com/a/16681225/5431797) – Ullauri

回答

4

您不需要創建實例;返回對MyTestCase類本身:

def initialize(): 
    return MyTestCase 
相關問題