Java/Selenium Tips from Angie Jones

The following recommendations come a "Code Smells" video (36:57) from Angie Jones (of Test Automation University). She shares example code from an ApplicationUnderTest that searches for and displays book titles. Here are some of her recommendations for tuning your code to follow best practices:


Write Short Classes

Long classes with too many lines of code are hard to read and even harder to refactor. Use these principles to make your classes shorter:
  • choice-cancel A class should not have many responsibilities
  • choice-yes A class should have one responsibility
  • choice-yes It should be easy to read the code and understand it
  • choice-yes It should be easy to find what you're looking for

Write Short Methods

Long classes are complicated and inflexible. Use these principles to make your classes shorter:
  • choice-cancel A method should not have many responsibilities
  • choice-yes A method should have a single responsibility
  • choice-yes It should be easy to read the code and understand the method
  • choice-yes It should be easy to know when to call the method

Use Conditional Waits, not Thread.sleep()

Because you have to guess what an appropriate time is to wait for UI elements to render, using Thread.sleep() means you will tend to overestimate how much waiting time is required. This might not be a big deal for a single test, but it can make automation code for an entire FeatureFile or test suite really slow. By using Selenium's WebDriverWait, you can wait.until(expected_conditions) are met, which means you never wait longer than it actually takes.

Build a Solid Framework using PageObjectModel

Your automation code should not need to know the structure of the ApplicationUnderTest, only what to check and what to assert.
  • choice-yes Use the standard ApacheMaven project structure with /main and /test subdirectories
  • choice-yes Under /main/java create one file to represent each page in the ApplicationUnderTest

Use Robust Location Identifiers

As the design of the UI changes, the xpath and css locators will change. Although you want to pick the locators that are the most likely to stay the same, you also want to write your code so that if the locators change, you only have to change them once (not many times). Use constructors to lock down variables that represent the page elements:
  • choice-yes private By searchBar = By.id("searchBar")

Use Annotation to Mark Setup, Teardown, and Test Types

  • choice-yes Put @BeforeClass ahead of your setup methods
  • choice-yes Put @AfterClass ahead of your teardown (closeApp) methods
  • choice-yes Mark test types using (for example) @Test, @SmokeTest, @RegressionTest

-- NicoleRadziwill - 10 Apr 2020
Topic revision: r5 - 16 Nov 2022, NicoleRadziwill
© 2020 Ultranauts - 75 Broad Street, 2nd Floor, Suite 206, New York, NY 10004 - info@ultranauts.co