4

I'm new for the selenium. I'm using same code for the login session, when i'm writing test case for every page . please tell me how to stop re-entering same code.. is there any other way to reuse it without mention those codes for every test case in every page.

6

Using WebDriver, you're free to use all the features of your programming language of choice. And that gives a lot of opportunities to structure your tests in such a way as to avoid code repetition.

If you're new to Selenium, I'd skip Page Object Model until you get comfortable with WebDriver basics. Until then, I would just wrap the frequently used code into functions and put those functions into a separate library/module that you can use in your test cases.

Let's assume you're using Python and you repeat the code for logging in all the time. For the sake of simplicity, let's also assume that navigation to the login page is taken care of separately in the test cases, and that the login form elements have stable, unique IDs. In such a case, you can write a function like this:

def login(user, password):
    user_field = driver.find_element_by_id("user")
    password_field = driver.find_element_by_name("password")
    login_button = driver.find_element_by_name("log-on")

    user_field.send_keys(user)
    password_field.send_keys(password)
    login_button.click()

Then, whenever you need to login from a test case, you just call your function:

login("myuser", "mypassword")

This is greatly simplified, but should give you an idea.

3

You can use the Page object model which includes methods as well as locators and come up with a method to do the login that you can call from all your tests.

For more information on the Page Object model details see these links -

Page Object Model

Page Object using selenium

  • Downvoting for providing link without explanation. – dzieciou Dec 16 '16 at 16:30
  • Added necessary details given that it was already accepted. – Michael Durrant Dec 17 '16 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.