A Few Tips to Improve Your Test Automation Scripts

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.
 
 

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.