Kate
Kate

Reputation: 1

Cannot invoke "org.openqa.selenium.WebDriver.findElement; End-To-End testing

I'm attempting to conduct end-to-end testing for login functionality using Selenium within IntelliJ. However, I've encountered an issue in the setUp phase. Whenever I execute the code, I consistently encounter the error:

java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)" because "SeleniumE2E.E2ETest.driver" is null

package SeleniumE2E;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class E2ETest {

  public static WebDriver driver;

  @BeforeMethod
   public void setUp() {
      try {
         System.setProperty("webdriver.gecko.driver", "C:\\Users\\picom\\Downloads\\geckodriver-v0.34.0-win64\\geckodriver.exe");

         FirefoxOptions options = new FirefoxOptions();
         options.addArguments("--headless");
         driver = new FirefoxDriver(options);
         driver.get("http://www.google.com");
         //driver.quit();
      } catch (Exception e) {
         e.printStackTrace();
         throw new RuntimeException("WebDriver initialization failed");
      }
   }

    @Test
    public void testLogin() {
        WebElement emailInput = driver.findElement(By.id("email"));
        emailInput.sendKeys("[email protected]");
        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.sendKeys("MAriya12!");

        WebElement loginButton = driver.findElement(By.xpath("//button[text()='Login']"));
        loginButton.click();

        String currentUrl = driver.getCurrentUrl();
        assertEquals("http://localhost:8080/Main.html", currentUrl);
    }

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

Here is my LoginDto and login.html:

package com.example.demo.dto;

public class LoginRequestDto {

    private String email;
    private String password;

    public LoginRequestDto() {
    }

    // Getters and Setters
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

<!DOCTYPE html>
<html>
<head>
    <title>User Login</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        h2 {
            color: #333;
            text-align: center;
        }
        form {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            margin: 20px auto;
        }
        label {
            display: block;
            margin: 10px 0 5px;
        }
        input[type=text], input[type=password] {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #008cba;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        button:hover {
            background-color: #005f73;
        }
    </style>
</head>
<body>
<h2>User Login</h2>
<form id="loginForm">
    <label for="email">Email:</label>
    <input type="text" id="email" name="email" required>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>

    <button type="button" onclick="login()">Login</button>
</form>
<p>Don't have an account? <a href="register">Register here</a>.</p>
<script>
    function login() {
        var email = document.getElementById("email").value;
        var password = document.getElementById("password").value;

        var loginData = {
            email: email,
            password: password
        };

        fetch('/api/user/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginData)
        })
            .then(response => {
                if (response.redirected) {
                    window.location.href = response.url;
                } else {
                    console.error('Login failed');
                    alert('Invalid email or password');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error occurred while logging in');
            });
    }
</script>
</body>
</html>

I've experimented with switching from the Google driver to Firefox and also attempted changing the access modifier from protected to public static for the WebDriver variable, but unfortunately, these adjustments didn't resolve the issue. Any other suggestions how to fix this error are appreciated.

Upvotes: -1

Views: 50

Answers (1)

Yaroslavm
Yaroslavm

Reputation: 4804

You are getting this error, because your @Test annotation is imported from wrong runner. Your import is:

import org.junit.jupiter.api.Test;

You use TestNG, so import should be from

import org.testng.annotations.Test;

As a result - you run your code under JUnit which doesn't recognise TestNG annotations.

Upvotes: 0

Related Questions