How to Create a Base Test Class in Java

 ✅ Step-by-Step: Creating a Base Test Class in Java

πŸ”Ή 1. Choose Your Testing Framework

We’ll use JUnit 5 (org.junit.jupiter) in this example. If you're using JUnit 4, let me know — it's slightly different.


πŸ”Ή 2. Create the Base Test Class

java

Copy

Edit

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.AfterEach;


public abstract class BaseTest {


    @BeforeEach

    public void setUp() {

        System.out.println("Base setup logic before each test...");

        // e.g., initialize shared resources, mock data, etc.

    }


    @AfterEach

    public void tearDown() {

        System.out.println("Base teardown logic after each test...");

        // e.g., clean up resources

    }


    // You can add shared helper methods here

    protected void log(String message) {

        System.out.println("LOG: " + message);

    }

}

πŸ”Ή 3. Extend the Base Class in Child Test Classes

java

Copy

Edit

import org.junit.jupiter.api.Test;


public class MyFeatureTest extends BaseTest {


    @Test

    public void testSomething() {

        log("Running testSomething");

        // actual test logic

    }


    @Test

    public void testAnotherThing() {

        log("Running testAnotherThing");

        // actual test logic

    }

}

πŸ”Ή 4. Optional: Add Common Mocks or Test Data

You can initialize mocks (e.g., with Mockito) or test data in the base class:


java

Copy

Edit

import org.mockito.MockitoAnnotations;


public abstract class BaseTest {

    @BeforeEach

    public void setUp() {

        MockitoAnnotations.openMocks(this);

        System.out.println("Mocks initialized");

    }

}

πŸ“ Notes

Use @BeforeEach and @AfterEach for test-level setup/teardown.


Use @BeforeAll and @AfterAll (with static methods) for class-level setup.


Mark the base class as abstract to avoid it being picked up as a test class.

Learn Selenium JAVA Course in Hyderabad

Read More

Reusable Methods in Java for Selenium Tests

How to Use Java Streams in Selenium Automation

Reading Data from Properties Files in Java

Writing Your First Selenium Test Case Using Java

Visit Our IHUB Talent Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Tosca for API Testing: A Step-by-Step Tutorial

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing