📅  最后修改于: 2023-12-03 15:05:44.323000             🧑  作者: Mango
Writing unit tests is an essential part of software development to ensure that the code is working as expected. However, web application testing requires testing in different web browsers since each browser behaves differently.
To achieve this, we can use the Unittest framework, which allows us to create test cases that can be run on multiple browsers.
First, let's install the necessary drivers for each browser that we want to test. For example, if we want to test with Chrome, Firefox, and Edge, we need to download their respective drivers from the following links:
Next, we need to install the necessary packages:
pip install selenium webdriver_manager unittest
From here, we can create a base test class that will handle the initialization and cleanup of the browser instances.
import unittest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
class BaseTest(unittest.TestCase):
def setUp(self):
self.drivers = {
'chrome': webdriver.Chrome(ChromeDriverManager().install()),
'firefox': webdriver.Firefox(executable_path=GeckoDriverManager().install()),
'edge': webdriver.Edge(EdgeChromiumDriverManager().install())
}
def tearDown(self):
for driver in self.drivers.values():
driver.quit()
In the above code, we import the necessary packages and create a dictionary of browser driver instances. In the setUp
method, we initialize the drivers and store them in the dictionary. In the tearDown
method, we iterate through the dictionary and quit each driver instance.
With this base test class, we can create our test cases and use the browser instances from the dictionary.
class MyTestCase(BaseTest):
def test_google(self):
for name, driver in self.drivers.items():
with self.subTest(name=name):
driver.get('https://www.google.com')
self.assertIn('Google', driver.title)
In the above code, we create a test case that opens Google in each browser instance and verifies that the page title contains the word "Google". Using self.subTest
allows us to see which browser each test case is running on.
In conclusion, using the Unittest framework and multiple browser drivers, we can create test cases that ensure our web applications work as expected in different browsers. By creating a base test class that handles the initialization and cleanup of the browser instances, our test cases become concise and reusable.