Time for action – moving Selenium steps into private methods to make tests maintainable - Selenium

Imagine that you just need to test one page on your site and you have quite a few tests for this page. A lot of the tests will be using the same code over and over again. This can be quite annoying to maintain if something changes on the page meaning we have to go through all the tests to fix this one issue. The way that we will fix this is to refactor the tests so they are simpler and therefore easier to read.

  1. Let us create a number of tests as follows:

  2. Using the previous examples, let's break these down.

  3. In both the examples, we can see that it is always opening the root of the site. Let's move that into its own private method. To do this in IDEA, you highlight the lines you want to refactor and then right-click. Use the context menu and then the extract method.

  4. Then you will see a dialog asking you to give the method a name. Give it something meaningful for the test. I have called it loadHomePage as you can see in the following screenshot:

  5. Now do the same for the other parts of the tests so that it makes the test look a lot more succinct.

  6. Your test class should look something like this:

What just happened?

We have just started making our tests a lot more maintainable. We saw how we can break this down into more succinct and readable tests that show intent rather than showing a test as a clump of Selenium calls. This also makes the tests a lot more manageable because if I were to change the link on the root from "Chapter2" to "Chapter 2", I would need to only fix it in one place rather than n places where n is the number of times that sequence is in the test class.

Now let's have a look at how we can use the Page Object Pattern for creating a DSL over the site.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Selenium Topics