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

猜你喜欢

转载自www.cnblogs.com/fancy0158/p/10051576.html