Skip to content
Go back

Test Automation - Improve Code Readability Using Enumeration

Published:

Introduction

In this article, I will review the implementation of enumeration that will help us improve our code readability.

Programing languages: Java

Automation Framework: Selenium

What is Enumeration?

FromOracle documentation :

Anenum typeis a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Because they are constants, the names of an enum type’s fields are in uppercase letters.

In the Java programming language, you define an enum type by using theenumkeyword

Implementation

First will take a look at a simple Selenium code that navigates to a menu option.

In the page object class, we identify a list of menu items and create a method that navigates to an option using a value that represents the option index.

@FindBy(css = ".menu")
private List<WebElement> menuItems;

public void selectMenuItem(int item) {
    menuItems.get(item).click();
}

In the test class, the usage of the navigation method is:

somePage.selectMenuItem(5);

We need to refactor the navigation method in order to improve the readability, we need to create an enum with values that represents the menu options:

public enum MenuOption {
    FIRST_OPTION(0), SECTOND_OPTION(1);

    private final int value;

    MenuOption(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

Then we can refactor our navigation method in the page object class:

@FindBy(css = ".menu")
private List<WebElement> menuItems;

public void selectMenuItem(MenuOption menuOption) {
    menuItems.get(menuOption.getValue()).click();
}

In the test class, the usage of the refactored navigation method is:

somePage.selectMenuItem(MenuOption.FIRST_OPTION)

Our test code now looks more readable using enumeration to define our menu navigation options instead of using the list indexes.

In conclusion

In this article, we reviewed the usage of enumeration, we refactored a navigation method and saw the improvement of our code readability.

Happy testing!


Suggest Changes

Have a challenge? Let's Talk


Previous Post
Test Automation - Improve Code Readability Using Java 13 Text Blocks
Next Post
Test Automation - How To Show Current Test Name Before Each Test