2011-05-09 54 views
1
import .... 

class Test1: 

    @classmethod 
    def setUpClass(self): 
    ... 

    def test_something(self): 
    ... 

    @classmethod 
    def tearDownClass(self): 
    ... 

class Test2: 

    @classmethod 
    def setUpClass(self): 
    ... 

    def test_anotherthing(self): 
    ... 

    @classmethod 
    def tearDownClass(self): 
    ... 

if __name__ == '__main__': 
    unittest2.main() 
+2

是的,你爲什麼不嘗試一下:)順便說你的類應該從'單元測試繼承。 TestCase' – mouad 2011-05-09 09:31:27

回答

1

是的。你爲什麼不給它一個旋風?

下面是一個例子,在我的測試類從unittest.TestCase繼承和測試故意失敗:

#!/usr/bin/env python 

import unittest 

class TestAddition(unittest.TestCase): 

    def test_addition(self): 
     self.assertEquals(3, 1 + 1) 

class TestSubtraction(unittest.TestCase): 

    def test_subtraction(self): 
     self.assertEquals(3, 1 - 1) 

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

% ./t.py 
FF 
====================================================================== 
FAIL: test_addition (__main__.TestAddition) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "./t.py", line 8, in test_addition 
    self.assertEquals(3, 1 + 1) 
AssertionError: 3 != 2 

====================================================================== 
FAIL: test_subtraction (__main__.TestSubtraction) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "./t.py", line 13, in test_subtraction 
    self.assertEquals(3, 1 - 1) 
AssertionError: 3 != 0 

---------------------------------------------------------------------- 
Ran 2 tests in 0.002s 

FAILED (failures=2) 
3

當然,這是可能的,只要確保它們從unittest.TestCase繼承。然後,unittest.main將發現並運行它們。

您還可以通過使用unittest.TestLoader().loadTestsFromTestCaseunittest.TestLoader().loadTestsFromNames方法在文件中運行一些測試。

相關問題