Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
Selenium JavaAI

How to Automate Selenium Login Tests With ChatGPT

Learn how to automate Selenium login tests with ChatGPT. Explore prompts, code walkthroughs, debugging tips, and best practices for better test generation.

Author

Vipul Gupta

May 27, 2026

Automating login tests is one of the most common tasks I work on in Selenium automation. It saves time, reduces manual errors, and validates authentication flows to catch issues early.

With tools like ChatGPT, this process has become even faster. It enables engineers to generate, debug, and refine Selenium login tests using simple natural language prompts.

Overview

How Do You Automate Login Tests With Selenium and ChatGPT?

The process runs in four steps, from writing the prompt to running a passing test in Eclipse:

  • Prompt with context: Specify your Java tech stack, target login URL, POM structure, and explicit wait requirements. The more context you give ChatGPT, the less hallucinated and off-target the output.
  • Review the generated output: ChatGPT returns four files: BaseTest.java for driver setup, LoginPage.java for locators and actions, LoginTest.java for the test case, and testng.xml for suite configuration. Review each before running.
  • Set up and execute: Place each file in its correct package inside the Maven project, update the login credentials in LoginTest.java with valid test account values, and run the suite via TestNG in Eclipse.
  • Debug with ChatGPT: When a test fails, paste the full stack trace into the same ChatGPT thread. It identifies the root cause, such as a broken locator or a timing issue, and suggests a precise fix.

How Do You Author and Maintain Selenium Login Tests With AI?

To author and maintain Selenium login tests, you can leverage Generative AI testing tools like TestMu's KaneAI, which authors, executes, and maintains tests from natural language, with self-healing locators, reusable login modules, and TOTP support without manual intervention.

What Do You Need Before Using ChatGPT for Selenium Login Tests

You need ChatGPT access, basic Selenium Java and TestNG knowledge, Page Object Model familiarity, and a configured Maven project in Eclipse or IntelliJ before generating your first login test.

For a hands-on reference on test setup, see the guide on how to automate login page using Selenium WebDriver. Here is what each prerequisite covers:

  • Comfort with ChatGPT prompting: You should be able to clearly describe what you want in simple language. You don't need perfect prompts, just clarity in your instructions.
  • Basic Selenium with Java: Understand how Selenium WebDriver works and how to identify web elements using locators like ID, XPath, or CSS.
  • TestNG fundamentals: Have a working idea of how TestNG annotations for Selenium WebDriver work and how common annotations like @Test, @BeforeMethod, and @AfterMethod are used.
  • Familiarity with Page Object Model (POM): Knowing how the Page Object Model in Selenium Java separates locators from test logic will help you better understand and organise the generated scripts.
  • Ready automation setup: Your project should already be set up in an IDE (like Eclipse or IntelliJ) with all dependencies configured, so you can directly run the code.

Project Setup

Follow the steps below to set up the Selenium Java TestNG project in Eclipse IDE.

Step 1. Launch Eclipse IDE and create a new Maven project named ChatGPTLoginTestDemo.

Step 2. Open the pom.xml file and add Selenium and TestNG Maven dependencies. The updated pom.xml would look like below:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ChatGPTLoginTestDemo-1</groupId>
    <artifactId>ChatGPTLoginTestDemo-1.0.0</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ChatGPTLoginTestDemo</name>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.21.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.9.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
Note

Note: Generate Selenium tests for login scenarios using natural language with KaneAI. Get Started Free

How to Prompt ChatGPT to Generate Selenium Login Tests

ChatGPT generates all parts of a Selenium login test, including POM files, locators, and TestNG annotations, when prompted with tech stack details, framework expectations, and the target URL.

All of this depends on prompt quality. In my experience, a vague prompt gets vague code.

A well-structured prompt sets context, gives ChatGPT the right constraints, and significantly cuts hallucination. Here is what that difference looks like in practice.

Here is what I got when I sent a vague prompt with no context:

Generate a Selenium test automation script to automate a login page.

As you can see from ChatGPT's generated response, it was completely off: it assumed a different framework and language.

  • The programming language used is Python, while we are using Java in this case.
  • The script does not follow POM, and setup/teardown methods are also not implemented.
  • The URL and web element locators used are all dummy and hallucinated.
  • Cloud execution support is also not added.

One thing I always remind myself: ChatGPT-generated code is never 100% production-ready. Every time I use it, I do a review pass before running anything.

Updated prompt with required information:

Write a Selenium Java TestNG test case using Page Object Model for the login flow of https://ecommerce-playground.lambdatest.io/

I have already created a project for the same in Eclipse IDE and added dependencies in pom.xml.

Requirements:
- Share the project structure to add packages and Java class files.
- Create a separate Page Object class for locators.
- Include locators for email, password, and login button.
- Add support for cloud execution on the TestMu AI platform.
- Follow best practices like explicit waits, setup and teardown methods.

ChatGPT returns a detailed response matching every requirement in the prompt. Copy the output into your project and make any minor adjustments before execution.

How Do You Run a ChatGPT-Generated Selenium Login Test

Copy the ChatGPT-generated files into your project structure, update credentials in LoginTest.java, then right-click LoginTest.java and select Run As TestNG Test in Eclipse to execute.

Using the structured prompt above, ChatGPT returns four files: BaseTest.java, LoginPage.java, LoginTest.java, and testng.xml. Start by creating the project structure in Eclipse. The folder layout should look like this:

ChatGPTLoginTestDemo
├── src
│   ├── main
│   │   └── java
│   │       ├── base
│   │       │   └── BaseTest.java
│   │       └── pages
│   │           └── LoginPage.java
│   └── test
│       └── java
│           └── tests
│               └── LoginTest.java
├── pom.xml
├── testng.xml
├── target
├── test-output
├── JRE System Library [JavaSE-11]
├── Maven Dependencies
└── TestNG

Next, copy and paste the code in each file from the ChatGPT response and make the changes if required.

// BaseTest.java
package base;

import java.net.URL;
import java.time.Duration;
import java.util.HashMap;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class BaseTest {
    protected WebDriver driver;

    private static final String HUB_URL = "https://hub.lambdatest.com/wd/hub";

    @BeforeMethod
    public void setUp() throws Exception {
        ChromeOptions browserOptions = new ChromeOptions();
        HashMap<String, Object> ltOptions = new HashMap<>();
        ltOptions.put("username", System.getenv("LT_USERNAME"));
        ltOptions.put("accessKey", System.getenv("LT_ACCESS_KEY"));
        ltOptions.put("project", "ChatGPT Selenium Login Tests");
        ltOptions.put("build", "selenium-login-demo");
        ltOptions.put("name", "Login Test");
        browserOptions.setCapability("LT:Options", ltOptions);
        driver = new RemoteWebDriver(new URL(HUB_URL), browserOptions);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");
    }

    @AfterMethod
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Code Walkthrough: BaseTest.java

setUp() builds a ChromeOptions object and attaches an LT:Options capability map containing your TestMu AI LT_USERNAME and LT_ACCESS_KEY environment variables. It then creates a RemoteWebDriver pointed at the TestMu AI hub, maximizes the window, sets an implicit wait, and opens the login URL. It runs before every test via @BeforeMethod.

The second method is tearDown(), which closes the remote browser session once test execution completes. It is annotated with @AfterMethod so it runs after each test.

// LoginPage.java
package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;

public class LoginPage {
    private WebDriver driver;
    private WebDriverWait wait;

    private By emailField = By.id("input-email");
    private By passwordField = By.id("input-password");
    private By loginButton = By.xpath("//input[@value='Login']");
    private By myAccountText = By.xpath("//h2[text()='My Account']");

    public LoginPage(WebDriver driver) {
        this.driver = driver;
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }

    public void enterEmail(String email) {
        WebElement emailElement = wait.until(
            ExpectedConditions.visibilityOfElementLocated(emailField));
        emailElement.sendKeys(email);
    }

    public void enterPassword(String password) {
        WebElement passwordElement = wait.until(
            ExpectedConditions.visibilityOfElementLocated(passwordField));
        passwordElement.sendKeys(password);
    }

    public void clickLogin() {
        WebElement loginBtn = wait.until(
            ExpectedConditions.elementToBeClickable(loginButton));
        loginBtn.click();
    }

    public boolean isLoginSuccessful() {
        return wait.until(
            ExpectedConditions.visibilityOfElementLocated(myAccountText)).isDisplayed();
    }

    public void login(String email, String password) {
        enterEmail(email);
        enterPassword(password);
        clickLogin();
    }
}

Code Walkthrough: LoginPage.java

This is the POM file for the login page. Because I included the target URL in the prompt, ChatGPT returned real locators, not hallucinated placeholders.

It added action methods for all three elements: email input, password input, and the login button, each wrapped in explicit waits as instructed. It also added an assertion to validate successful login.

Finally, a login() method bundles all those actions into a single callable from any test class.

// LoginTest.java
package tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import base.BaseTest;
import pages.LoginPage;

public class LoginTest extends BaseTest {
    @Test
    public void verifyLogin() {
        LoginPage loginPage = new LoginPage(driver);
        loginPage.login("[email protected]", "password123");
        Assert.assertTrue(loginPage.isLoginSuccessful(), "Login Failed!");
    }
}

Code Walkthrough: LoginTest.java

This is the main test class. It uses the @Test annotation and calls the LoginPage object to perform and verify the login flow via the login() method.

Update the username and password with valid test account credentials before running.

<!-- testng.xml -->
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="ChatGPT Login Suite">
    <test name="Login Test">
        <classes>
            <class name="tests.LoginTest"/>
        </classes>
    </test>
</suite>

Code Walkthrough: testng.xml

Since the prompt to ChatGPT specifies that we are using the TestNG framework, it responds by adding testng.xml in the required format to be able to execute the test cases.

Execution and Output:

To execute the ChatGPT-generated Selenium login test, right-click LoginTest.java in the Project Explorer and select Run As → TestNG Test. Alternatively, right-click testng.xml and select Run As → TestNG Suite to run all configured tests.

Before running, update the placeholder credentials in LoginTest.java to valid test account values. A successful run will show a green pass bar in the IDE like below.

TestNG execution output for ChatGPT-generated Selenium login test in Eclipse IDE

How to Debug Failed Login Tests With ChatGPT

ChatGPT helps debug Selenium login test failures by reviewing error stack traces you share, identifying root causes like incorrect locators, and suggesting targeted code fixes to resolve them quickly.

Even when using ChatGPT, tests fail. In my experience, invalid or brittle locators are the most common culprit, followed by slow-loading elements.

In one of my runs, a locator from ChatGPT's response was wrong. Running the test produced this error:

Selenium login test failure showing NoSuchElementException in Eclipse IDE console

I passed this stacktrace back to ChatGPT on the same thread where it generated the code and asked it to fix the issue. The prompt I used:

I am getting the following error when executing the Selenium login test you generated. Can you identify the root cause and suggest the fix?

[paste the error stacktrace here]

ChatGPT responds by suggesting the corrected web element locator to fix the issue.

The issue is actually very simple, but very common in Selenium tests.

Root Cause
Your error says: By.id("emai");
But the correct locator should be: By.id("input-email");

You have a typo in your locator (emai instead of email), which is why
Selenium cannot find the element and throws:
NoSuchElementException which leads to TimeoutException (because explicit
wait keeps retrying)

Fix: Update your locator in LoginPage.java

Incorrect:
private By emailField = By.id("emai");

Correct:
private By emailField = By.id("input-email");

How to Author and Maintain Selenium Login Tests With TestMu's KaneAI

KaneAI by TestMu AI (Formerly LambdaTest) is a Generative AI testing tool that authors, executes, and maintains tests from natural language. No prompt engineering, no code review pass, and no manual locator fixes after every UI update.

It is built for automation engineers who need more than code generation: teams that want tests authored, run, and kept working across sprints without constant manual intervention.

To get started, check out this guide to author your first web test with KaneAI.

Key capabilities:

  • Self-Healing Locators: When the login page UI changes and locators break, KaneAI detects the failure, identifies the updated element, and patches the test automatically. No stack trace copying, no re-prompting.
  • Reusable Login Modules: Converts common flows like login into reusable blocks any test in the suite can call. Define it once and reference it everywhere, instead of duplicating setup across every new test file.
  • TOTP and 2FA Support: Generates TOTP codes directly from secret keys, making two-factor authentication login flows testable end-to-end without any external dependencies.
  • Natural Language Test Authoring: Describe login scenarios such as invalid credentials, locked accounts, or session expiry in natural language. KaneAI resolves the steps, selectors, and assertions without a prompt-review-fix loop.
  • Selenium Code Export: Exports tests to Selenium, Playwright, or Cypress. If you are already on the Selenium Java stack from this tutorial, the output maps directly to what you already know.
...

What Are the Best Practices for Generating Selenium Login Tests With ChatGPT

The best practices are writing structured prompts with your tech stack and framework, providing the target URL or HTML, reviewing every generated file before execution, and specifying explicit waits in the prompt.

Four practices I follow every time I use ChatGPT for Selenium test generation:

  • Structured Prompts: Always structure prompts clearly with tech stack, framework expectations, design patterns like POM, and expected output. This keeps ChatGPT focused and cuts down on hallucinated or off-target responses significantly.
  • WebPage HTML References: Give ChatGPT a reference to the target page: the URL if it is public, or the raw HTML if it is not. Real DOM context produces accurate locators and prevents the flaky failures that come from hallucinated selectors.
  • Human Code Review: Never blindly trust generated code. Always review and refactor as needed. ChatGPT is an assistant, not a replacement for your engineering judgment.
  • Additional Instructions: Define the usage of best practices like explicit waits and robust web element locators in the prompt to enforce optimised and resilient code.

These practices help get the best out of ChatGPT, but ChatGPT still cannot execute tests, heal broken locators, or trigger runs inside a CI/CD pipeline. KaneAI is purpose-built for exactly those three gaps.

Conclusion

ChatGPT cuts the time from requirement to runnable Selenium login test significantly. The prompting patterns, code walkthroughs, and debugging approach in this tutorial give you a repeatable workflow you can apply to any login flow in your project.

Prompt quality is the single biggest variable in the output you get. The more context you provide, such as tech stack, target URL, and framework conventions, the less you fix afterward.

Author

Vipul Gupta is a Sr. Lead SDET at Zupee with over 9 years of experience in functional and automation testing. He has built 10+ automation projects from scratch covering web, API, and mobile applications. Vipul is skilled in Selenium, Appium, Rest Assured, Playwright, Java, Python, Pytest, BDD, TDD, Maven, Jenkins, TestNG, and JUnit. He has successfully led end-to-end QA efforts, including setting up teams from scratch and managing a 15-member QA team to ensure manual and automation testing run in parallel from day one. Vipul graduated in B.Tech CSE from CGC College of Engineering and is followed by 3,000+ QA and SDET professionals on LinkedIn, reflecting his strong influence in the testing community.

Open in ChatGPT Icon

Open in ChatGPT

Open in Claude Icon

Open in Claude

Open in Perplexity Icon

Open in Perplexity

Open in Grok Icon

Open in Grok

Open in Gemini AI Icon

Open in Gemini AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

Frequently Asked Questions on Selenium Login Automation with ChatGPT

Did you find this page helpful?

More Related Hubs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests