在前面的分享中,我們分別講了unittest的相關流程以及相關斷言,那麼很多人,都會問了unittest的用例,應該如何執行呢,這次,我們就來看看,unittest用例如何執行。
首先,我們可以使用pycharm執行。我們試著右鍵,發現不是我們想要的。

我們試著在if 右鍵的綠色箭頭執行發現,效果是一樣的。

那麼我們到底在pycharm應該如何執行呢。
我們點選右上角的

選擇edit Configurations...
看了下,我們直接執行的是tests,我們需要配置下

首先我們選中Python tests下面的,然後點選-號。
然後在python點選+

選中python。點選,然後我們去選中我們指令碼的路徑即可

選中後,點選apply,然後我們再點執行。
右鍵還是點選if前面的綠色按鈕都可以

我們看下結果

準確了執行我們所有的用例。
當然了,我們除了上面的方法還有,在終端執行。
可以直接開啟,cmd或者終端,然後屬於python test.py 執行,或者點選pycharm的Terminal,和終端一樣的效果。
直接python testdemoone.py 對應的名稱就可以。
我們要看測試執行的詳細資訊怎麼辦呢,其實也很簡單。

可以列印出來詳細的資訊,比如測試用例的名稱。是否執行成功。
我們也可以執行模組
python -m unittest testdemoone
執行結果如下

我們也可以執行具體的模組的類
python -m unittest testdemoone.TestDemo
結果如下

也可以執行具體的方法
python -m unittest testdemoone.TestDemo.testone
結果如下

獲取幫助選項
python -m unittest -h


假如我們在執行測試用例的時候,我們想要測試用例執行到錯誤的地方就停止怎麼辦呢,其實很簡單
python testdemoone.py -f
我們把testdemoone.py 修改下:
import unittest
class TestDemo(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testone(self):
self.assertEqual(1,2)
def testtwo(self):
self.assertEqual(1,1)
if name=="main":
unittest.main()
那麼我們執行下面的命令,如何展示呢
python testdemoone.py -f
結果如下

我們可以看到,當執行失敗後,程式執行就直接退出了。
上文文中的testdemoone.py如下:
import unittest
class TestDemo(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testone(self):
self.assertEqual(1,2)
def testtwo(self):
self.assertEqual(1,1)
if name=="main":
unittest.main()
假如我們想要探索執行目錄下面所有的測試用例,我們應該怎麼去執行呢,可以在目錄這麼執行.
python -m unittest discover
展示如下:

在我們去探索執行目錄下面,我們要想看到和執行單個檔案一樣的詳細資訊怎麼辦呢。其實也很簡單,直接加-v即可。
python -m unittest discover -v
執行結果如下:

我們要探索制定檔案下的怎麼辦呢,其實很簡單
python -m unittest discover -v -s testone
執行結果如下

我們要模糊匹配檔案怎麼辦
命令如下
python -m unittest discover -v -s testone -p 'test*.py'
結果如下:
