Python:unittest简单使用

2025-09-02  本文已影响0人  紫荆逸

代码:使用方式


import unittest

class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print('这是 类级 setUpClass()')

    @classmethod
    def tearDownClass(cls):
        print('这是类级 tearDownClass()')

    def setUp(self):
        print('这是函数级 setUp()')

    def tearDown(self):
        print('这是函数级 tearDown()')

    def test_one(self):
        print('这是第一条用例')

    def test_two(self):
        print('这是第二条用例')

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

以百度搜索为例:

# 第二节 8.2.2----百度搜索/unittest_baidu3.py ---setUpClass

import unittest
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By


class Test_Baidu(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        self.driver = webdriver.Firefox()

    @classmethod
    def tearDownClass(self):
        self.driver.quit()

    def setUp(self):
        self.driver.get('https://www.baidu.com/')

    def tearDown(self):
        pass

    def test_search_cn(self):
        self.driver.find_element(By.ID, "chat-textarea").send_keys('思课帮')
        sleep(2)
        self.driver.find_element(By.ID, "chat-submit-button").click()
        sleep(2)
        self.assertEqual('思课帮_百度搜索', self.driver.title)


    def test_search_en(self):
        self.driver.find_element(By.ID, "chat-textarea").send_keys('Thinkerbang')
        sleep(2)
        self.driver.find_element(By.ID, "chat-submit-button").click()
        sleep(2)
        self.assertEqual('Thinkerbang_百度搜索', self.driver.title)

if __name__ == '__main__':
    unittest.main()
上一篇 下一篇

猜你喜欢

热点阅读