selenium unittest in python

To write Selenium unittests in Python, you need to follow these steps:

  1. Import unittest and Selenium modules
main.py
import unittest
from selenium import webdriver
47 chars
3 lines
  1. Create a class for your test case that inherits from Python's unittest.TestCase
main.py
class MyTestCase(unittest.TestCase):
37 chars
2 lines
  1. In the setUp() method of the class, create an instance of the Selenium WebDriver
main.py
def setUp(self):
    self.driver = webdriver.Chrome()
54 chars
3 lines
  1. Write test methods, each starting with the word test_
main.py
def test_search_in_google(self):
    self.driver.get("https://www.google.com")
    self.driver.find_element_by_name("q").send_keys("selenium")
    self.driver.find_element_by_name("btnK").click()
    assert "selenium" in self.driver.page_source
245 chars
6 lines
  1. In the tearDown() method of the class, close the web driver instance
main.py
def tearDown(self):
    self.driver.close()
44 chars
3 lines
  1. Finally, use Python's unittest.main() to run the tests in the command line
main.py
if __name__ == '__main__':
    unittest.main()
47 chars
3 lines

gistlibby LogSnag