Automating Task Management Testing with Selenium WebDriver: A Comprehensive Guide

Automating Task Management Testing with Selenium WebDriver: A Comprehensive Guide



Introduction

This article aims to describe how I used Selenium WebDriver to automate the tests for the Task Manager Plus UI system. This project involved creating automated tests for the Login and Task screens, ensuring that all essential functionalities were working correctly. Test automation is crucial for increasing efficiency, reducing human errors, and ensuring continuous software quality. Throughout this article, I will present the detailed steps of how the tests were implemented, the challenges faced, and the results obtained.


Project Context

The TaskManagerPlus-UI project is a front-end application developed to interact with the TaskManagerPlus-API. This project aims to provide an intuitive and efficient user interface for task management, allowing users to create, view, edit, and delete tasks easily. The importance of this project lies in its ability to facilitate task organization and tracking, providing an enhanced and productive user experience.


Project Objectives

  • Ensure the quality and functionality of the task screen.
  • Demonstrate skills in automated testing using Selenium WebDriver.
  • Optimize testing time by automating repetitive tasks.


Tools and Technologies Used

To set up the automated testing environment, I used the following tools and technologies:

  • Selenium WebDriver: To automate browser interaction.
  • TestNG: To structure and execute tests.
  • ExtentReports: To generate detailed test reports.
  • Apache POI: For handling Excel files.
  • Log4j: For logging.
  • Spring Boot: To facilitate the development of Java applications.


Project Architecture

The architecture of the Task Manager Plus UI project was designed to be modular and organized, facilitating maintenance and future expansion. The project is structured as follows:

  • Config: Contains configuration classes, including ConfigReader.java for reading configurations and JdbcTemplateSingleton.java for managing database connections.
  • Drivers: Includes the DriverFactory.java class, responsible for instantiating and managing the browser drivers used in tests.
  • Listeners: Contains the TestListener.java class, which implements listeners to capture events during test execution.
  • Pages: This package follows the Page Object Model (POM) pattern and contains classes representing the different pages of the system, such as BasePage.java, LoginPage.java, TaskRegisterPage.java, TaskSearchPage.java, among others.
  • Reports: Includes the ExtentReportManager.java class to manage the generation of test reports using ExtentReports.
  • Tests: Contains the test classes, such as LoginTest.java, TaskEditTest.java, TaskRegisterTest.java, and TaskSearchTest.java, which implement the test scenarios for the system's functionalities.
  • Utils: Includes utility classes, such as BrowserUtils.java, ExcelUtils.java, ScreenshotUtils.java, among others, which provide auxiliary functionalities for the tests.
  • Webdriver: Package used to manage the browser drivers.


Project Structure in Eclipse

The project structure in Eclipse is organized as follows:

Project Structure in Eclipse


The structure helps in organizing the code into logical modules, making it easier to manage and extend the project in the future. This organization ensures that each component of the project is easily accessible and maintainable.


Database Configuration

The project uses a MySQL database for testing. The database configurations are defined in the application-test.properties file, as shown in the image below:

# Database settings for tests spring.datasource.url=jdbc:mysql://localhost:3306/taskmanagerplusapi spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true        


Test Description

To ensure the quality and functionality of the Task Manager Plus UI system, various automated tests were conducted using Selenium WebDriver. This article describes the main tests performed, focusing on the login screen and task functionalities. Below are code examples and screenshots of the tests in action.


Login Test with Valid Credentials

The objective of this test is to verify if the system allows login with valid credentials and redirects the user to the application's main page.

Test Code:

/**
 * Test for User Login:
 * 
 * <p>Scenario: Login with valid credentials and verify successful login.</p>
 * <p>Steps:</p>
 * <ol>
 * <li>Navigate to the login page.</li>
 * <li>Read login credentials from an Excel file.</li>
 * <li>Enter the username and password into the respective fields.</li>
 * <li>Click the login button.</li>
 * <li>Wait for the URL to change to the application's home page.</li>
 * <li>Verify that the current URL matches the expected URL.</li>
 * <li>Verify the presence of specific elements on the dashboard (user link and logout button).</li>
 * </ol>
 * <p>Expected Result: The login should be successful, the URL should change to the application's home page, and the specific elements unique to the dashboard should be present.</p>
 */
@Test
public void testLogin() {
    LoginPage loginPage = navigateToLoginPage();

    // Read credentials from Excel file
    String username = excelUtils.getCellDataByColumnName("LoginCredentials", 1, "Username");
    String password = excelUtils.getCellDataByColumnName("LoginCredentials", 1, "Password");

    ExtentReportManager.getTest().log(Status.INFO, "Entering login credentials");
    loginPage.enterLogin(username);
    loginPage.enterPassword(password);

    ExtentReportManager.getTest().log(Status.INFO, "Clicking the login button");
    loginPage.clickLoginButton();

    // Explicit wait to ensure the URL has changed to the expected one
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    ExtentReportManager.getTest().log(Status.INFO, "Waiting for URL to change to the application page");
    wait.until(ExpectedConditions.urlToBe(ConfigReader.getProperty("urlApplicationHome")));

    // Getting the expected URL from the config file
    String expectedUrl = ConfigReader.getProperty("urlApplicationHome");
    String actualUrl = driver.getCurrentUrl();

    ExtentReportManager.getTest().log(Status.INFO, "Verifying the login was successful");
    Assert.assertEquals(actualUrl, expectedUrl, "The login was not successful.");

    // Additional check: Verify if the specific elements unique to the dashboard are present
    DashboardPage dashboardPage = new DashboardPage(driver);
    ExtentReportManager.getTest().log(Status.INFO, "Verifying presence of user link on the dashboard");
    Assert.assertTrue(dashboardPage.isUserLinkPresent(), "The user link on the dashboard was not found.");

    ExtentReportManager.getTest().log(Status.INFO, "Verifying presence of logout button on the dashboard");
    Assert.assertTrue(dashboardPage.isLogoutButtonPresent(), "The logout button on the dashboard was not found.");
}
        


Test Steps:

  1. Navigate to the login page.
  2. Read the login credentials from an Excel file.
  3. Enter the username and password into the respective fields.
  4. Click the login button.
  5. Wait for the URL to change to the application's home page.
  6. Verify that the current URL matches the expected URL.
  7. Verify the presence of specific elements on the dashboard (user link and logout button).

Expected Result: The login should be successful, the URL should change to the application's home page, and the specific elements on the dashboard should be present.

Screenshot:

Login Page


Additional Note:

In this test, the API was intentionally stopped to display an error in the report, as shown in the image below. This demonstrates how the system handles connection failures and ensures that appropriate error messages are displayed when the application cannot communicate with the API.

Error Screenshot:

Server not found


Error Description:

In the login test with valid credentials, the API was deliberately stopped to check if the system displays an appropriate error message when it cannot connect to the API. As expected, the test failed to reach the correct URL, indicating that the system responded as designed for this scenario.

Error Details Captured by ExtentReport:

Login Page - API Down - ExtentReport


Task Edit Test

The objective of this test is to verify if an existing task can be successfully edited and if the changes are reflected correctly.

Test Code:

/**
 * Test for Editing and Verifying a Task:
 * 
 * <p>Scenario: Edit an existing task and verify the changes.</p>
 * <p>Steps:</p>
 * <ol>
 * <li>Start the test and log the initial status.</li>
 * <li>Enter new title, description, and due date for the task.</li>
 * <li>Click on another element to trigger form validation.</li>
 * <li>Set the task as completed.</li>
 * <li>Click the save button.</li>
 * <li>Verify that a success message is displayed.</li>
 * <li>Log the success of the task update.</li>
 * <li>Navigate back to the task search page and search for the updated task by its title.</li>
 * <li>Validate that the updated task is present in the search results.</li>
 * <li>Verify that the task's description, due date, and completion status match the updated values.</li>
 * <li>Ensure that the edit and delete buttons are present for the task.</li>
 * <li>Log the success of the task verification.</li>
 * </ol>
 * <p>Expected Result: The task should be successfully updated with the new details and should be present in the search results with the correct information. The edit and delete buttons should be present.</p>
 */
@Test
public void editAndVerifyTask_shouldSucceed() {
    ExtentReportManager.getTest().log(Status.INFO, "Starting test: editAndVerifyTask_shouldSucceed");

    String newTaskTitle = "Test Task A Edited";
    String newTaskDescription = "Test Description A Edited";
    String newTaskDueDate = "2024-07-20";

    taskRegisterPage.enterTitle(newTaskTitle);
    taskRegisterPage.enterDescription(newTaskDescription);
    taskRegisterPage.enterDueDate(newTaskDueDate);
    
    // Click on another element to trigger form validation
    taskRegisterPage.clickTitleInput();
    
    taskRegisterPage.setCompleted(true);

    // Click the save button
    taskRegisterPage.clickSaveButton();

    NotificationPage notificationPage = new NotificationPage(driver);
    WebElement successMessage = notificationPage.getConfirmRemoveMessage();
    Assert.assertNotNull(successMessage, "The success message should be displayed after task update.");
    Assert.assertEquals(successMessage.getText().replace("×", "").trim(), "Successfully Updated", "The success message should indicate that the task was updated.");

    ExtentReportManager.getTest().log(Status.PASS, "Task update test passed");
    logger.info("Task update test passed");

    // Navigate back to the task search page and verify the updated task
    taskSearchPage = navigateToTaskPage();
    taskSearchPage.enterTitle(newTaskTitle);
    taskSearchPage.clickSearchButton();

    WebElement taskRow = taskSearchPage.waitForTaskRow(newTaskTitle, wait);
    Assert.assertNotNull(taskRow, "The updated task should be present in the search results.");

    String description = taskSearchPage.getTaskDescription(taskRow);
    Assert.assertEquals(description, newTaskDescription, "The description should match.");

    String dueDate = taskSearchPage.getTaskDueDate(taskRow);
    Assert.assertEquals(dueDate, newTaskDueDate, "The due date should match.");

    String completed = taskSearchPage.getTaskCompletedStatus(taskRow);
    Assert.assertEquals(completed, "Yes", "The task should be completed.");

    Assert.assertTrue(taskSearchPage.hasEditButton(taskRow), "The edit button should be present.");
    Assert.assertTrue(taskSearchPage.hasDeleteButton(taskRow), "The delete button should be present.");

    ExtentReportManager.getTest().log(Status.PASS, "Task verification test passed");
    logger.info("Task verification test passed");
}
        


Test Steps:

  1. Start the test and log the initial status.
  2. Enter a new title, description, and due date for the task.
  3. Click on another element to trigger form validation.
  4. Set the task as completed.
  5. Click the save button.
  6. Verify that a success message is displayed.
  7. Log the success of the task update.
  8. Navigate back to the task search page and search for the updated task by its title.
  9. Validate that the updated task is present in the search results.
  10. Verify that the task's description, due date, and completion status match the updated values.
  11. Ensure that the edit and delete buttons are present for the task.
  12. Log the success of the task verification.

Expected Result: The task should be successfully updated with the new details and should be present in the search results with the correct information. The edit and delete buttons should be present.

Screenshot:

Edit Task


Task Registration Test

The objective of this test is to verify if a new task can be successfully registered in the system by filling in all the fields.

Test Code:

    /**
     * Test to verify that a task can be created with all fields filled.
     * 
     * <p>Scenario: Fill in all fields on the task registration form and save the task.</p>
     * <p>Steps:</p>
     * <ol>
     * <li>Enter a title in the title input field.</li>
     * <li>Enter a description in the description input field.</li>
     * <li>Enter a due date in the due date input field.</li>
     * <li>Check the completed checkbox.</li>
     * <li>Click the save button.</li>
     * </ol>
     * <p>Expected Result: The task should be successfully created and a success message should be displayed.</p>
     */
    @Test
    public void createTask_withAllFieldsFilled_shouldSucceed() {
        ExtentReportManager.getTest().log(Status.INFO, "Starting test: createTask_withAllFieldsFilled_shouldSucceed");

        taskRegisterPage.enterTitle("Test Task title create withAllFieldsFilled");
        taskRegisterPage.enterDescription("Test Task description create withAllFieldsFilled");
        taskRegisterPage.enterDueDate("2024-07-16");
        taskRegisterPage.setCompleted(true);
        taskRegisterPage.clickSaveButton();
        
        // Verify the success message
        NotificationPage notificationPage = new NotificationPage(driver);
        WebElement successMessage = notificationPage.getConfirmRemoveMessage();
        Assert.assertNotNull(successMessage, "The success message should be displayed after deletion.");
        Assert.assertEquals(successMessage.getText().replace("×", "").trim(), "Successfully Created", "The success message should indicate that the task was created.");
        
        ExtentReportManager.getTest().log(Status.PASS, "Task creation with all fields filled test passed");
        logger.info("Task creation with all fields filled test passed");
    }        


Test Steps:

  1. Enter a title in the title input field.
  2. Enter a description in the description input field.
  3. Enter a due date in the due date input field.
  4. Check the completed checkbox.
  5. Click the save button.

Expected Result: The task should be successfully created, and a success message should be displayed.

Screenshot:

Additional Explanation:

The title of the image is marked as "Edit Task" because, after registering a task, it can be edited. This test verifies if the task was created successfully, and once the task is saved, the edit functionality becomes available, allowing the user to modify the task details as needed.


Task Search Test

Here is a screenshot of the automated tests executed in Eclipse for the task search functionality:


Task Consult


In this test, we validated various functionalities related to task search, including filters by title, description, and completion status. The screenshot shows the test results, highlighting the tests that passed and any failures encountered.


Results and Benefits

The automated tests implemented in the Task Manager Plus UI system have provided significant improvements in software quality. Below are the main benefits observed:


Improvement in Software Quality

  • Rapid Bug Detection: Automated tests allowed for the quick identification of bugs and functional issues, ensuring that failures were fixed before impacting end users.
  • Comprehensive Coverage: Automation enabled the execution of a wide range of tests on various critical functionalities, such as login and task management, ensuring that all important parts of the system worked correctly.
  • Consistency in Testing: Automated test execution ensured that each test was performed consistently, eliminating the variability introduced by manual testing.


Efficiency and Time Savings

  • Reduction in Testing Time: Test automation significantly reduced the time required to execute repetitive tests, allowing hundreds of tests to be run in minutes instead of the hours needed for manual testing.
  • Increased Productivity: With automation, testers were able to focus on more complex and creative tasks, such as creating new test scenarios and analyzing results, rather than performing repetitive and time-consuming tests.


Challenges and Lessons Learned

During the development of automated tests for the Task Manager Plus UI system, I faced several challenges that impacted the progress of the project. Below, I describe these challenges and how I overcame them, along with the lessons learned and best practices that reinforced my knowledge.

Challenges Faced

  • Lack of Time: One of the main challenges was the lack of time to build the project. In a week and a half, I worked about 40 hours on the project, which included building it from scratch, defining the architecture, choosing the language, and prioritizing the screens to be tested.
  • Frontend Modifications: It was necessary to make some changes to the application's frontend, mainly in creating IDs used by Selenium to facilitate test automation.
  • Maven Library Issues: I encountered difficulties with some Maven libraries, which required configuration adjustments to ensure compatibility and proper test functioning.

Implemented Solutions

  • Efficient Time Management: Prioritizing the most critical functionalities to be tested first and optimizing the available time to ensure the delivery of a robust set of automated tests.
  • Frontend Adjustments: Implementing unique identifiers (IDs) in the user interface elements to facilitate test automation with Selenium.
  • Dependency Resolution: Reviewing and adjusting dependencies in the pom.xml, ensuring that all necessary libraries were correctly configured and functioning.

Lessons Learned and Best Practices

  • Separation of Concerns: Reinforcing the importance of separating class responsibilities to improve maintainability and code reuse. Each class should have a single, clear responsibility.
  • Detailed Test Reports: Creating detailed test reports, including passed and failed tests, proved essential for quick and accurate result analysis. Detailed reports facilitate problem identification and informed decision-making.
  • Automation as a Quality Tool: Reinforcing the value of test automation as a crucial tool for ensuring continuous software quality, saving time and resources in the long run.

These lessons and practices reinforced my knowledge and allowed me to deliver a high-quality project, even with limited time. When well implemented, test automation not only improves software quality but also increases the efficiency of the development process.


Conclusion

In this article, we discussed the importance and benefits of test automation, especially using Selenium WebDriver for the Task Manager Plus UI system. Below, we recap the main points covered:

Implementation of Automated Tests

We explored how to set up and execute automated tests to verify the functionality of login and task management, ensuring the system's integrity.

Project Architecture

We described the modular structure of the project, highlighting how the efficient organization of classes and packages facilitates maintenance and future expansion.

Challenges and Solutions

We shared the main challenges faced, such as the lack of time and issues with Maven libraries, and the solutions implemented to overcome them.

Lessons Learned

We reinforced the importance of best practices, such as the separation of class responsibilities and the creation of detailed test reports.

Test automation is an essential practice that can save time and increase efficiency, allowing for the quick detection of errors and ensuring continuous software quality. I encourage all developers and QA teams to implement automated tests in their projects to gain these benefits.


Next Steps

My goal for the future is to expand the coverage of automated tests by creating new tests for the Province, Group, Group Permission, and User pages. Additionally, I plan to improve the compatibility of the tests, ensuring that they can be executed not only in Google Chrome but also in other popular browsers, such as Mozilla Firefox and Microsoft Edge.

These enhancements will ensure greater robustness and versatility of the tests, guaranteeing that the Task Manager Plus UI system functions correctly in different browsing environments, providing a consistent and reliable experience for all users.


Acknowledgments

I would like to thank my cat, who has always been by my side, supporting me with its meows. To my wife, for allowing me to talk to myself and sometimes utter inappropriate words to the computer/code/problem. And also to Bell, my internet provider, for maintaining a stable connection throughout the entire process.


Contact

Feel free to connect with me on LinkedIn. I'm always open to new connections, feedback, and collaboration opportunities. Here is the link to my profile: LinkedIn - Maicon Fang.

Check out the complete project on GitHub. Feel free to explore, fork, or contribute. Here is the link to the repository: GitHub - taskmanagerplus-selenium.

Additionally, you can find the repositories for the API and the user interface used in this project at the following links: GitHub - taskmanagerplus-api and GitHub - taskmanagerplus-ui. Feel free to explore, fork, or contribute


Interaction

I would love to receive feedback, questions, and suggestions from you all! Your feedback is valuable to me as my goal is to improve my skills and provide more useful content. Please share your thoughts in the comments. Your ideas will help me improve and deliver better content. ??


要查看或添加评论,请登录

Maicon Fang的更多文章

社区洞察

其他会员也浏览了