How to Use Python to Generate Test Cases for Java

Meenakshi Agarwal
By
Meenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
10 Min Read

In this HowTo tutorial, we’ll use Python to generate test cases for Java classes. For this purpose, Python provides an external module namely, javalang, so we’ll utilize it for test case generation. Since Python is much more user-friendly and easy to use than any other programming language, so why should we as a developer not take benefit out of it?

Introduction – Using Python Code for Java Test Case Generation

Whether you have a basic core Java class or working on a SpringBoot microservice project, this Python script will help you in creating test cases on the fly. Our goal is to help and serve both the developer and Software testing community.

Logic Behind the Python Script Generating Test Cases for Java Classes

Our Python script uses a library called javalang to understand Java code. It figures out the names of functions, what kind of information they need (parameters), and what they give back (return types). Then, it makes simple test cases for each function, like filling in the blanks for inputs and checking if the results match what we expect. This helps speed up the process of creating tests for Java code.

Sample Java Class Files for Demo Purpose

Let’s assume, we have a simple Java project that consists of two Java class files. For testing purposes, you must save the below with the given names in your Python code’s current working directory.

// YourClass.java - The Employee entity class
public class Employee {
    private String fName;
    private String lName;
    private int age;
    private String role;

    public Employee(String fName, String lName, int age, String role) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
        this.role = role;
    }

    public String getFullName() {
        return fName + " " + lName;
    }

    public int getAge() {
        return age;
    }

    public String getRole() {
        return role;
    }
}

The next file is where we have the logic to perform some operations using the entities in the previous Java file.

// Employee.java (A simple Employee class for demonstration):
public class Employee {
    private String fName;
    private String lName;
    private int age;
    private String role;

    public Employee(String fName, String lName, int age, String role) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
        this.role = role;
    }

    public String getFullName() {
        return fName + " " + lName;
    }

    public int getAge() {
        return age;
    }

    public String getRole() {
        return role;
    }
}

We have the sample Java classes ready for testing our Python script that will take these files as input and generate the test cases. Please note you will be running the script for your own Java classes. But firstly, you can test with the given files to be just sure if the code is working or not.

Main Python Script to Generate Test Cases for Java Classes

Before we get to the next step, make sure you run the pip command to install the javalang library.

pip install javalang

Now, let’s have the main code we need to create test cases without any manual effort.

# Script: py_test001.py
import os
import javalang

# To dynamically get the methods avaiable in Java class files
def get_method_info(java_code):
    tree = javalang.parse.parse(java_code)
    method_info = [(method.name, method.parameters) for _, method in tree if isinstance(method, javalang.tree.MethodDeclaration)]
    return method_info

# To generate test cases using the meta data from methods
def gen_test_cases(method_info):
    test_cases = []

    for method_name, method_params in method_info:
        # Generate test cases based on method parameters and return types
        test_case = f"public void test_{method_name}() {{\n"

        # Extract parameters and create input values
        if method_params:
            input_vals = ', '.join([f"{param.type.name} {param.name}" for param in method_params])
            test_case += f"    {input_vals} = ...; // Provide suitable inputs\n"
        else:
            test_case += "    // No parameters for this method\n"

        # Test case logic - you can customize this part
        test_case += f"    {method_name}Result = YourClass.{method_name}();\n"
        test_case += "    // Assert statements for the expected result\n"

        test_case += "}\n"
        test_cases.append(test_case)

    return test_cases

if __name__ == "__main__":
    # Get all Java files in the current directory
    java_files = [file for file in os.listdir() if file.endswith(".java")]

    for java_file in java_files:
        with open(java_file, 'r') as file:
            java_code = file.read()

        # Extract method names and parameters
        method_info = get_method_info(java_code)

        # Generate test cases
        test_cases = gen_test_cases(method_info)

        if test_cases:
            # Print generated test cases to the console
            print(f"Test cases for {java_file}:")
            for test_case in test_cases:
                print(test_case)
            print("\n")

So, we have the script ready to take the input from Java files lying in the current working directory. As you have already saved the given Java classes, so similarly save the above script as py_test001.py. You however are free to give any names you want for these files.

Our script is generic as it dynamically generates test cases for all methods present in the Java class, regardless of their names or the number of methods. It loops through files in the current directory to get all the Java files present.

Testing & Execution

Our test bed was Ubuntu 22.04 and Python3 for testing this Python script. You can be sure of it by checking below.

Python and Ubuntu Version to Generate Test Cases-for Java Class

Now, run the following command to execute our script.

python3 py_test001.py

At present, the script outputs the generated test cases on the console. However, you can make a little modification to the code to save the result to a file.

Test cases for Employee.java:
public void test_getFullName() {
    // No parameters for this method
    getFullNameResult = YourClass.getFullName();
    // Assert statements for the expected result
}

public void test_getAge() {
    // No parameters for this method
    getAgeResult = YourClass.getAge();
    // Assert statements for the expected result
}

public void test_getRole() {
    // No parameters for this method
    getRoleResult = YourClass.getRole();
    // Assert statements for the expected result
}

Test cases for YourClass.java:
public void test_getTotalEmp() {
    // No parameters for this method
    getTotalEmpResult = YourClass.getTotalEmp();
    // Assert statements for the expected result
}

public void test_getEmpFullName() {
    int row, int col = ...; // Provide suitable inputs
    getEmpFullNameResult = YourClass.getEmpFullName();
    // Assert statements for the expected result
}

public void test_calcAvgAge() {
    // No parameters for this method
    calcAvgAgeResult = YourClass.calcAvgAge();
    // Assert statements for the expected result
}

FAQs On Using Python for Dynamically Generating Test Cases

Here are some FAQs that might be relevant to the topic:

Q: Can this script handle Java nested classes with complex structures and methods?
A: Yes, the script uses javalang to parse and understand the Java code, making it suitable for classes with various structures and nested methods.

Q: How does the script handle Java classes with multiple files?
A: The script reads all Java files in the current directory, generating test cases for each file. This allows it to handle Java classes spread across multiple files.

Q: Can I tweak the generated test cases for specific methods?
A: Absolutely! The script gives you a starting point, and you can easily adjust the test case logic as needed.

Q: Does the script work with any Python or Java version?
A: The script is designed to be Python-version-agnostic. It uses javalang to analyze Java code, making it compatible with various Python versions and any version of Java.

Q: How can I run this script on my machine?
A: Save the script as a .py file and place it in the same directory as your Java files. Run it using a Python interpreter (python script_name.py), and it will generate test cases for your Java classes.

Feel free to ask any specific questions you might have about the script and its usage.

Conclusion

This tutorial introduces a Python script that makes testing Java classes easy. Using an external library, javalang the script smartly figures out what methods a Java class has, creating test cases without needing specific method names. We hope you use it for your Java applications and get some benefits.

However, it’s just an idea we wanted to share, you can use it or extend it for your use cases. feel free to ask any queries or suggestions you like to share.

Happy Coding,
Team TechBeamers

Share This Article
Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *