package com.mockobjects.util;

import junit.framework.*;
import java.lang.reflect.*;

/**
 * Singleton to fill in a JUnit Test composite for use in a suite method.
 */

public class SuiteBuilder {

    public static TestSuite buildTest(Class allTestsClass) {
        return buildTest(allTestsClass, new ErrorLogger());
    }

    public static TestSuite buildTest(
        Class allTestsClass,
        ErrorLogger logger) {
        TestSuite result = new TestSuite();

        Method[] methods = allTestsClass.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            Method m = methods[i];
            String name = m.getName();

            if (isAddMethod(m)) {
                try {
                    Object[] args = new Object[] { result };
                    m.invoke(allTestsClass, args);
                } catch (Exception ex) {
                    logger.error("Error creating Test from " + name, ex);
                }
            }
        }

        return result;
    }

    public static boolean isAddMethod(Method m) {
        String name = m.getName();
        Class[] parameters = m.getParameterTypes();
        Class returnType = m.getReturnType();
        return parameters.length == 1
            && name.startsWith("add")
            && returnType.equals(Void.TYPE)
            && Modifier.isPublic(m.getModifiers())
            && Modifier.isStatic(m.getModifiers());
    }
}
