1. 程式人生 > >Appium+python的單元測試框架unittest(4)——斷言

Appium+python的單元測試框架unittest(4)——斷言

在我們編寫的測試用例中,測試步驟和預期結果是必不可少的。當我們執行測試用例時,得到一個執行結果,需要和預期結果對比從而判斷測試是否通過。

一、斷言方法

斷言:將實際結果和預期結果進行比較,從而判定測試用例執行是否通過。

單元測試中斷言是不可或缺的,單元測試框架一般會提供豐富的斷言方法。unittest框架的TestCase類提供斷言的方法可以用於測試結果的判斷:

實際應用:

    def test_add(self):
        self.driver.find_element_by_name("1").click()
        self.driver.find_element_by_name(
"5").click() self.driver.find_element_by_name("+").click() self.driver.find_element_by_name("8").click() self.driver.find_element_by_android_uiautomator("new UiSelector().text(\"=\")").click() result = self.driver.find_element_by_class_name('android.widget.EditText').text #
從應用中獲取計算結果 self.assertEqual(int(result), 23, 'The result is wrong') # 斷言,判斷計算結果是否正確 self.driver.find_element_by_name("CLR").click()

來自官網:

All the assert methods (except assertRaises()assertRaisesRegexp()) accept a msg argument that, if specified, is used as the error message on failure.

除了assertRaises()assertRaisesRegexp()以外,所有的斷言方法都接收一個msg作為失敗時的資訊輸出。可以自定義該msg引數,若無自定義,則預設為None

  • 斷言特性:當有測試用例斷言驗證失敗時,將會退出程式,後面的程式不再執行。

二、斷言異常

我們的用例中可能會有預期結果為丟擲異常,assertRaises()方法可以斷言異常

import unittest

class DivZeroTestCase(unittest.TestCase):

    def test_should_raise_exception(self):
        with self.assertRaises(ZeroDivisionError):
            1 / 0

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

執行結果通過

$ python test_exception.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
  • 上面的例子斷言了當0作為除數的時候會丟擲ZeroDivisionError
  • 斷言異常是有套路的,使用with語句加assertRaises,assertRaises的引數中傳入預期的異常(這些異常可能需要先import進來),在with的子句中放上會丟擲異常的語句或表示式

官網:https://docs.python.org/2/library/unittest.html#assert-methods