Using unittest Framework with Selenium in Python
✅ Using unittest Framework with Selenium in Python
π§ 1. What is unittest?
Python’s built-in unittest module is a framework for writing and running tests. It helps structure test cases and reports results clearly.
π What is Selenium?
Selenium is a powerful tool for automating web browsers, widely used for testing web applications.
π§± Basic Project Structure
Copy
Edit
project/
├── tests/
│ └── test_login.py
├── requirements.txt
└── ...
π¦ Install Required Packages
Make sure you have the required libraries:
bash
Copy
Edit
pip install selenium
You’ll also need a WebDriver (like ChromeDriver or GeckoDriver) installed and added to your system’s PATH.
π§ͺ Sample Test with unittest + Selenium
python
Copy
Edit
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
import time
class LoginTest(unittest.TestCase):
def setUp(self):
# Set up the WebDriver
self.driver = webdriver.Chrome() # or use Service(ChromeDriverManager().install())
self.driver.get("https://example.com/login") # Replace with your login page URL
def test_login_valid_user(self):
driver = self.driver
# Locate input fields and enter values
driver.find_element(By.ID, "username").send_keys("testuser")
driver.find_element(By.ID, "password").send_keys("password123")
driver.find_element(By.ID, "login-button").click()
time.sleep(2) # Wait for login response
self.assertIn("dashboard", driver.current_url) # Assertion: did we reach dashboard?
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
⚙️ How to Run the Tests
From your terminal:
bash
Copy
Edit
python tests/test_login.py
You’ll see output like:
markdown
Copy
Edit
.
----------------------------------------------------------------------
Ran 1 test in 3.001s
OK
π‘ Best Practices
Use setUpClass and tearDownClass for setup shared across tests.
Use explicit waits (WebDriverWait) instead of time.sleep() for reliability.
Organize tests in separate files and use test discovery (python -m unittest discover).
Integrate with CI tools (e.g., GitHub Actions, Jenkins) for automated testing.
π Advanced Tips
Use Page Object Model (POM) to separate page logic from test logic.
Use headless mode for faster testing (e.g., webdriver.Chrome(options=opts)).
Combine with pytest if you want more advanced test features.
✅ Conclusion
Using unittest with Selenium in Python gives you a solid foundation for writing maintainable, automated browser tests. It’s ideal for testing login forms, workflows, and UI behavior—all within Python’s standard testing framework.
Learn Selenium Python Training in Hyderabad
Read More
How to Read Data from Excel or CSV for Selenium Test Automation
Selenium with Python for Testing Login Pages
Taking Screenshots with Selenium WebDriver in Python
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment