Java Reflection Utility to Execute All Non‑Main Methods in a Package for API Testing

This article presents a Java reflection‑based utility that automatically discovers all classes in a specified package and executes each of their non‑main methods, enabling comprehensive API test execution without manually invoking each test case.

FunTester
FunTester
FunTester
Java Reflection Utility to Execute All Non‑Main Methods in a Package for API Testing

During API testing with HttpClient, the author faced the issue of having to manually run every test method across all classes in a test package; to solve this, they created a Java utility that uses reflection to locate all classes in a given package and invoke every non‑main method automatically.

package source;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class excuteSource extends SourceCode {
    public static void main(String[] args) {
        excuteAllMethodInPackage("pie.normal");
    }

    /** 
     * Execute all non‑main methods in the package
     */
    public static void excuteAllMethodInPackage(String packageName) {
        List<String> classNames = getClassName(packageName);
        if (classNames != null) {
            for (String className : classNames) {
                String path = packageName + "." + className;
                excuteAllMethod(path); // execute all methods
            }
        }
    }

    /** Get all public methods of an object */
    public static Method[] getAllMethod(Object object) {
        Class<?> class1 = object.getClass();
        class1.getName();
        Method[] methods = class1.getDeclaredMethods();
        return methods;
    }

    /** Execute all methods of an object, excluding main */
    public static void excuteAllMethod(Object object) {
        Class<?> class1 = object.getClass();
        Method[] methods = class1.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals("main")) {
                continue;
            }
            executeMethodByName(method.getName(), class1.getName());
        }
    }

    /** Execute all methods of a class, excluding main */
    public static void excuteAllMethod(String path) {
        Class<?> c = null;
        Object object = null;
        try {
            c = Class.forName(path);
            object = c.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Class<?> class1 = object.getClass();
        Method[] methods = class1.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals("main")) {
                continue;
            }
            executeMethodByName(method.getName(), class1.getName());
        }
    }

    /** Execute a method by name using reflection */
    public static void executeMethodByName(String mehtod, String path) {
        Object obj = null;
        Method method = null;
        String className = null;
        try {
            Class<?> c = Class.forName(path);
            obj = c.newInstance();
            className = c.getCanonicalName();
            method = c.getMethod(mehtod);
        } catch (Exception e) {
            output("Reflection execution error!", e);
        }
        try {
            output("Executing " + className + " class's " + method.getName() + " method");
            method.invoke(obj);
        } catch (Exception e) {
            output("Reflection method invocation exception!", e);
        }
    }

    /** Get all class names under a package */
    public static List<String> getClassName(String packageName) {
        List<String> fileNames = new ArrayList<>();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        String packagePath = packageName.replace(".", "/");
        URL url = loader.getResource(packagePath);
        if (url == null || !"file".equals(url.getProtocol())) {
            output("Failed to get class names!");
            return fileNames;
        }
        File file = new File(url.getPath());
        File[] childFiles = file.listFiles();
        for (File childFile : childFiles) {
            String path = childFile.getPath();
            if (path.endsWith(".class")) {
                path = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
                fileNames.add(path);
            }
        }
        return fileNames;
    }
}

Note: The main method should be filtered out to avoid unintentionally invoking other classes' main methods.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaReflection
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.