Java is widely used in software testing because it's simple, reliable, and supports powerful testing tools like Selenium and JUnit. It helps testers write automation scripts to test websites and applications easily.
With Java, you can create reusable test cases, connect to databases, and build full automation frameworks—making it a top choice for QA and test engineers.
Why Choose Java for Testing
Here is the Reasons why we choose Java for testing:
- Java’s statically-typed nature helps catch errors at compile-time, ensuring more stable test code.
- Widely used frameworks like JUnit, TestNG, Selenium, and RestAssured support comprehensive testing needs.
- Java’s “write once, run anywhere” principle makes it reliable for cross-platform testing.
- Java integrates well with tools like Maven, Jenkins, Gradle, and various CI/CD pipelines.
1. Setting Up Java
Before starting to learn Java we need to Install Java on our system.
Verify Installation:
Run the command in the terminal to confirm Java is properly installed:
java -version
2. Java Variables
In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated. Variables store test inputs, expected results, or objects like WebDriver instances in Selenium.
The below example demonstrates the variable declaration in Java
Java
// Demonstarting how to declare and use a variable in Java
class Geeks {
public static void main(String[] args) {
// Declaring and initializing variables
// Integer variable
int age = 25;
// String variable
String name = "GeeksforGeeks";
// Double variable
double salary = 50000.50;
// Displaying the values of variables
System.out.println("Age: " + age);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
}
OutputAge: 25
Name: GeeksforGeeks
Salary: 50000.5
3. Java Keywords
In Java, keywords are the reserved words that have some predefined meanings and are used by the Java compiler for some internal process or represent some predefined actions.
These keywords are essential to the Java syntax and cannot be redefined or used in any other context.
Java
// Java Program to demonstrate Keywords
class Geeks {
public static void main(String[] args)
{
// Using final and int keyword
final int x = 10;
// Using if and else keywords
if(x > 10){
System.out.println("Failed");
}
else {
System.out.println("Successful demonstration"
+" of keywords.");
}
}
}
4. Java Data Types
Java is statically typed and also a strongly typed language because each type of data, such as integer, character, hexadecimal, packed decimal etc. is predefined as part of the programming language, and all constants or variables defined for a given program must be declared with the specific data types.
Java has two categories in which data types are divided:
1. Primitive Data Type: These are the basic building blocks that store simple values directly in memory.
2. Non-Primitive Data Types (Object Types): These are reference types that store memory addresses of objects.
Data types in JavaExample:
Java
public class DataTypesExample {
public static void main(String[] args) {
// Primitive Data Types
int age = 30; // int
double price = 99.99; // double
char grade = 'A'; // char
boolean isAvailable = true; // boolean
// Non-Primitive Data Types
String name = "Alice"; // String (Object)
int[] numbers = {1, 2, 3, 4}; // Array (Object)
Person person = new Person("Bob", 40); // Class (Object)
// Displaying Values
System.out.println("Primitive Types:");
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Availability: " + isAvailable);
System.out.println("\nNon-Primitive Types:");
System.out.println("Name: " + name);
System.out.println("Numbers: " + java.util.Arrays.toString(numbers));
System.out.println("Person: " + person.name + ", Age: " + person.age);
}
}
// Custom class representing a Person
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
OutputPrimitive Types:
Age: 30
Price: 99.99
Grade: A
Availability: true
Non-Primitive Types:
Name: Alice
Numbers: [1, 2, 3, 4]
Person: Bob, Age: 40
Output:
Data Tpes in Java5. Conditional Statements
Conditional statements in Java, like if
, else if
, and else
, are used to control the flow of execution based on specific conditions. The if
statement checks a condition, and if it's true, it executes the corresponding block of code.
The else if
statement provides additional conditions to check if the initial if
condition is false. If none of the conditions are true, the else
block is executed. This is useful in test automation for making decisions based on test results or specific conditions encountered during the test execution.
Java
public class ConditionalStatement{
public static void main(String[] args) {
// Primitive Data Types
int age = 25;
if (age <= 12) {
System.out.println("Child.");
} else if (age <= 19) {
System.out.println("Teenager.");
} else if (age <= 35) {
System.out.println("Young adult.");
} else {
System.out.println("Adult.");
}
// Output: Young adult.
}
}
Conditionals handle test scenarios or validate web elements in Selenium.
6. Loops in Java
In Java, there are three types of Loops, which are listed below:
for Loop
The for loop is used when we know the number of iterations (we know how many times we want to repeat a task). The for statement includes the initialization, condition, and increment/decrement in one line.
while Loop
A while loop is used when we want to check the condition before executing the loop body.
do-while Loop
The do-while loop ensures that the code block executes at least once before checking the condition.
Example of for, while and do-while loop:
Java
public class LoopExample {
public static void main(String[] args) {
// For Loop Example
String[] browsers = {"Chrome", "Firefox", "Edge"};
System.out.println("For Loop: Iterating through browsers");
for (int i = 0; i < browsers.length; i++) {
System.out.println("Testing on: " + browsers[i]);
}
// While Loop Example
int counter = 1;
System.out.println("\nWhile Loop: Printing numbers less than 5");
while (counter < 5) {
System.out.println("Counter: " + counter);
counter++;
}
// Do-While Loop Example
int attempt = 1;
System.out.println("\nDo-While Loop: At least 1 attempt");
do {
System.out.println("Attempt: " + attempt);
attempt++;
} while (attempt <= 3);
}
}
OutputFor Loop: Iterating through browsers
Testing on: Chrome
Testing on: Firefox
Testing on: Edge
While Loop: Printing numbers less than 5
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Do-While Loop: At le...
7. Java Strings
In Java, a String is the type of object that can store a sequence of characters enclosed by double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowing for various operations such as concatenation, comparison, and manipulation.
Example:
Java
public class Stringexample {
public static void main(String[] args) {
String s = "GfG";
System.out.println(s.charAt(1)); // Output: f
String s1 = s + s.charAt(0);
System.out.println(s1); // Output: GfGG
}
}
Strings handle URLs, element locators, or assertions in Selenium.
8. Java Arrays
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data.
Java
public class Array {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
for (int i : arr) {
System.out.println(i * 2);
}
// Output: 2 4 6 8
}}
These Java basics you need to know before starting any software testing using java and frameworks like JUnit, TestNG, or Selenium.
When choosing test tools for Java, there are several powerful frameworks that can help automate testing and provide detailed reports on the test results.
Here are some of the most popular test tools for Java:
1. Selenium Java Test
Selenium is a powerful tool for automating browser interactions, and it can be effectively used with Java for web testing. With Selenium WebDriver, you can programmatically control a browser to simulate user interactions like clicking buttons, entering text, or opening a website.
Java example to open and close a website using Selenium:
Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumTest {
public static void main(String[] args) {
// Set the path to your chromedriver
System.setProperty("webdriver.chrome.driver", "C:\\Users\\path of chromedriver\\drivers\\chromedriver.exe");
// Create an instance of ChromeDriver
WebDriver driver = new ChromeDriver();
// Open the website
driver.get("https://www.geeksforgeeks.org");
// Wait for 5 seconds
try {
Thread.sleep(5000); // Simulate waiting for a few seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
// Close the browser
driver.quit();
}
}
Output:
Selenium test outputHere we used the Java fundamentals like:
- Variables: driver stores the WebDriver instance.
- Strings: URL for navigation.
- OOP: ChromeDriver class instantiation.
- Methods: get() and quit() perform browser actions.
2. JUnit
JUnit is an open-source testing framework that plays a crucial role in Java development by allowing developers to write and run repeatable tests. It helps ensure that your code functions correctly by verifying that individual units of code behave as expected.
Example of a JUnit test:
Java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestMathOperations {
public int add(int a, int b) {
return a + b;
}
@Test
public void testAdd() {
assertEquals(5, add(2, 3));
}
@Test
public void testAddNegative() {
assertEquals(0, add(-1, 1));
}
}
Here we implemented unit test using java fundamentals:
import org.junit.Assert;
: Imports JUnit's assertion methods.import org.junit.Test;
: Imports the @Test
annotation.public class CalculatorTest { ... }
: Defines the test class.@Test
: Marks the testAddition()
method as a test case.Calculator calculator = new Calculator();
: Creates an instance of the class being tested.int result = calculator.add(2, 3);
: Calls the method under test.Assert.assertEquals(5, result);
: Asserts that the result of the addition is as expected.
3. TestNG
TestNG is a powerful testing framework that allows you to structure your tests efficiently. It supports parallel execution, data-driven testing (parameterization), and various other advanced features. Below is an example of using TestNG to perform a login test with Selenium.
Maven Dependency for TestNG:
First, you need to include the TestNG dependency in your pom.xml
file.
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.1</version> <!-- Replace with the latest version -->
<scope>test</scope>
</dependency>
Selenium TestNG Example: Test Login
This example include how to use TestNG for automating a login test with Selenium WebDriver.
Java
package Tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class LoginPageTestex {
private WebDriver driver;
private String url = "https://www.saucedemo.com/";
// Setup method to initialize WebDriver
@BeforeMethod
public void setUp() {
// Set up ChromeDriver
System.setProperty("webdriver.chrome.driver", "C:\\Users\\path of chromedriver\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
// Method to navigate to the login page
public void navigateToLoginPage() {
if (!driver.getCurrentUrl().equals(url)) {
driver.get(url);
}
}
// Method to perform login
public boolean performLogin(String username, String password) throws InterruptedException {
WebElement userName = driver.findElement(By.id("user-name"));
userName.sendKeys(username);
WebElement passWord = driver.findElement(By.id("password"));
passWord.sendKeys(password);
WebElement loginBtn = driver.findElement(By.id("login-button"));
loginBtn.click();
return true;
}
// Test method
@Test
public void testLogin() throws InterruptedException {
// Navigate to the login page
navigateToLoginPage();
// Perform login with valid credentials
performLogin("standard_user", "secret_sauce");
// Add assertions here to verify successful login
// For now, just sleep to let the test run
Thread.sleep(2000);
}
// Teardown method to close the browser after each test
@AfterMethod
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
Output
Output of selenium testng testIn test automation, Java fundamentals are used in different ways.
- Annotations:
@BeforeMethod
, @Test
, and @AfterMethod
manage the test lifecycle by setting up, running, and cleaning up after each test. - Variables/Strings: Used to store WebDriver instances and input data for the tests.
- Assertions: Validate the actual results against the expected outcomes to ensure test accuracy.
- Methods: Encapsulate setup, test execution, and teardown logic, making the code modular and maintainable.
Running Tests in IDEs
Use IDEs like IntelliJ IDEA or Eclipse that support Java automation frameworks for running tests.
- IntelliJ IDEA: Right-click on the test folder and select “Run Tests” (JUnit/TestNG). The results will appear in the Run window.
- Eclipse: Right-click the test file, select “Run As > JUnit Test” or “TestNG Test.” You can view the test results in the JUnit/TestNG tab.
Similar Reads
JUnit Testcases Preparation For a Maven Project The quality of a software project is the desired aspect always. Programmers write code and they will do unit testing, block level testing, and sometimes integration testing too. But they will provide a few examples alone for the use cases. For example, if they are finding a number is prime or not, m
4 min read
7 Best Testing Frameworks for Java Developers Java is one of the most popular languages for programming & development and a wide range of applications is developed in this particular language. And when an individual opts for making a career in Java, he is required to acquire the knowledge of testing frameworks also to develop secure and eff
5 min read
JUnit 5 â @RepeatedTest JUnit 5 is a powerful and flexible testing framework in the Java ecosystem, widely used for unit testing Java applications. It introduces several modern features that simplify testing, making it a preferred choice for developers. One of its common features is the @RepeatedTest annotation, which is d
5 min read
TestNG Tutorial TestNGÂ is an automation testing framework widely used across many projects. NG means âNext Generationâ and it is influenced by JUnit and it follows the annotations (@).Table of Content What is TestNG?PrerequisiteAdvantages of TestNGTestNG Basic To AdvanceConclusionFAQs on TestNG TutorialWhat is Test
3 min read
Types of Software Testing Software testing is a important of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performance, se
15+ min read
Types of Software Testing Software testing is a important of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performance, se
15+ min read