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:
- A class should not have many responsibilities
- A class should have one responsibility
- It should be easy to read the code and understand it
- 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:
- A method should not have many responsibilities
- A method should have a single responsibility
- It should be easy to read the code and understand the method
- 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.
Your automation code should not need to know the structure of the
ApplicationUnderTest, only what to check and what to assert.
- Use the standard ApacheMaven project structure with /main and /test subdirectories
- 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:
- private By searchBar = By.id("searchBar")
Use Annotation to Mark Setup, Teardown, and Test Types
- Put @BeforeClass ahead of your setup methods
- Put @AfterClass ahead of your teardown (closeApp) methods
- Mark test types using (for example) @Test, @SmokeTest, @RegressionTest
--
NicoleRadziwill - 10 Apr 2020