(616) 371-1037

[email protected]

A Few Tips to Improve Your Test Automation Scripts

January 24, 2022 - Oleg Kapustin

No Comments

Today I want to talk about how you can improve your test automation scripts, and give you two of my favorite tips on how to accomplish that. If you are new to test automation, these two tips will definitely help you. If you have some AQA (automated quality assurance) experience, I believe you will still find these tips useful as a way to verify that you are using these best practices in all of your test scripts.

Automated QA Tip 1: Don’t Be Afraid to Use XPath

There are many methods you can use to find elements on a page. Here are the classic rules used to pick the best one for your situation:

  • If the element has an ID, use the ID;
  • If there is a class name, use a class name;
  • If the element does not have an ID and class name – ask the developer to create an ID or class name for that element;
  • If coding changes are not possible, but you can use CSS to write a short selector, use CSS;
  • If all else fails, you can use XPath.

There is one more reason why people do not want to use XPath: it’s commonly thought that XPath is the slowest of the locator options. However, there are a lot of experiments that show that XPath is not always the slowest, and sometimes it is even the fastest. It all depends on many things the browser, how well-written the locator is, etc. Unless you’re doing thousands of selectors in your tests, there are probably a lot of other things that slow down our tests more than the selectors.

Some Tips for Writing XPath

If you decided to write XPath, use these tips below to do it better:

  • Never copy XPath from your browser. It looks ugly and unreadable. For instance, here is some ugly APath generated by the browser: /html/body/div/div[1]/div/div[1]/div/div[1]/div[3]/button
  • Try to write your XPath as short as it possible;
  • Instead of a long chain of slashes, use parent, child, and sibling relationships;
  • You should use the boolean operations AND, NOT, OR;
  • Start writing XPath from “//”.

Some Commands for Writing XPath

There are many commands you can use to write the perfect XPath, some of which you can see below:

  • text() – returns the text contained in the element;
  • contains(parameter, sought-for) – returns the element if it contains the desired one;
  • starts-with(parameter, sought-for) – returns elements starting with the desired one;
  • commands of relations:
    • sibling – returns the element that is at the same level;
      • preceding-sibling – returns the element that is above;
      • following-sibling – returns the element that located below;
    • parent;
    • child;
    • descendant (you can use “//” instead descendant);
    • ancestor.

XPath Examples

Below you can see some examples of how we can use the commands listed above to find an element when ID and Class are not possible.

Web pages and their elements usually contain a lot of text that we can use to create locators. For example, in order to find the link, we can use one of the following scripts:

//a[text() = ‘Forgot password’]

//a[@class=’link’ and contains(text(), ‘Forgot’)]

//a[contains(@class, ‘link’)]

//a[@class = ‘link’ and start-with(text(), ‘Forgot’)]

As you can see, these XPaths are readable and simple to write.

We can also use the element relation commands. Imagine that we need to find the element with the <a> tag in the picture above, and this element does not have any classes or other selectors.

//a[text() = ‘Forgot password’]/child::a

If you want to find some element using element relation commands you need to use the following pattern:

// start element / relation :: end element tag (filter)

Use these commands in your test automation scripts and after a while, you will understand that it’s not only convenient but can also help you write tests that are easier to read and maintain.

Automated QA Tip 2: Automatically Restart Failed Tests: or, How to Give Your Tests a Second Chance

The second tip relates to one of the main problems of test automation.

Very often we have a situation when our test automation scripts fail. This can be due to many reasons: server responds slower than usual, network issues, the test crashes without waiting for the page to load or the request is complete, etc. Sometimes we can solve it by re-running it manually, but overall, this is not a good idea.

Of course, it’s best to write tests that don’t fail unless the application isn’t working, but sometimes that is impossible. In those situations, to get rid of the need to manually re-run tests, we can simply write our test to automatically re-run themselves several times until they either succeed, or they reach a retry count.

To implement this, create a rule with the following script and put it in the web driver settings file of our project.

Using the variable “RETRY_COUNT” we can set the number of times our failed tests will be restarted. As you can see, in my tests this variable is 2, I think this is sufficient in most cases.

 

    /**
     * This script allows us to re-run failed tests any number of times or until the test succeeds.
     */
    @Rule
    public TestRule rerunRule = new TestRule() {
        public Statement apply(final Statement base,
                               final Description description) {
            return new Statement() {

                @Override
                public void evaluate() throws Throwable {

                    //Use the RETRY_COUNT to set the number of times our failed tests will be
                    // restarted
                    final int RETRY_COUNT = 2;

                    for (int i = 1; i <= RETRY_COUNT; i++) {
                        try {
                            base.evaluate();
                            System.out.println(description.getDisplayName()
                                    + ": was successful after " + i
                                    + " attempt(s)");
                            break;
                        } catch (Exception e) {
                            if (i == RETRY_COUNT) {
                                System.out.println(description.getDisplayName()
                                        + ": was not successful for " + i
                                        + " attempts");
                                throw e;
                            }
                        }
                    }
                }
            };
        }
    };

This approach can help you solve some intermittent problems and get fewer false positives in your tests.

Summary

I hope these two automated testing tips are helpful in your future work and empower you to write better test scripts.

I leave you with the most important rule for automated testers: “Do not write scripts that you do not intend to use in the future in your work“. For example, if you know that a page will be removed in the near future, you shouldn’t spend any time writing tests for this page. Following this rule will allow you to save time to write scripts for just the most important features.

 

 

Oleg Kapustin

Leave a comment

Your email address will not be published. Required fields are marked *