以下程序:單元測試在Python
import unittest
class my_class(unittest.TestCase):
def setUp(self):
print "In Setup"
self.x=100
self.y=200
def test_case1(self):
print "-------------"
print "test case1"
print self.x
print "-------------"
def test_case2(self):
print "-------------"
print "test case2"
print self.y
print "-------------"
def tearDown(self):
print "In Tear Down"
print " "
print " "
if __name__ == "__main__":
unittest.main()
給人的輸出:
>>> ================================ RESTART ================================
>>>
In Setup
-------------
test case1
100
-------------
In Tear Down
.In Setup
-------------
test case2
200
-------------
In Tear Down
.
----------------------------------------------------------------------
Ran 2 tests in 0.113s
OK
>>>
>>>
問題:
什麼意思:
if __name__ == "__main__": unittest.main()
?爲什麼我們有雙下劃線前綴爲
name
和main
?將在何處創建
my_class
的對象?
看到這個問題http://stackoverflow.com/questions/419163/what-does-if-name-main-do – HavelTheGreat 2015-02-10 18:08:34
1.一次提出一個問題。 2.前導雙尾下劃線用於指示*「魔術」對象或屬於用戶控制的命名空間「*,[PEP-0008](https://www.python.org/dev/peps/ PEP-0008 /#描述命名的樣式)。這可以防止它們與用戶的名字發生衝突(例如,您可以調用函數'main'或變量'name')。見例如http://stackoverflow.com/q/19216895/3001761 3.你是什麼意思*「where」* ?! – jonrsharpe 2015-02-10 18:12:41