mardi 19 mai 2015

Unable to get annotation in a server environment

Objective: trying to scan the org.junit.runners.Suite.SuiteClasses annotations in my test classes from a Web App.

I ran the code in JVM/as java program, and it runs perfectly fine, the following is a code snippet:

Example.class:

@RunWith(Suite.class)
@Suite.SuiteClasses({Test1.class})
public class Example {
    public String test() {// For testing print methods
        return "hi";
    }
}

In class that runs the scan:

File dir = <localtion_of_Example.class>;
List<URL> urlList = new ArrayList<URL>();
urlList.add(new File(dir).toURI().toURL());
URLClassLoader cl = new URLClassLoader(urlList.toArray(new URL[urlList.size()]));

Class<?> c = cl.loadClass("<package>.Example");
// Here I can print class methods

Suite.SuiteClasses annotation = c.getAnnotation(Suite.SuiteClasses.class);
if (annotation != null) {
    Class<?>[] suiteClassLst = annotation.value();
    for (Class<?> curSuiteClass : suiteClassLst) {
        System.out.println(curSuiteClass.getName());
    }
}

So the above prints <package>.Test1 as expected, but when I run the same piece in a server environment, even though it can load the class, it can print the method name, the annotation from

Suite.SuiteClasses annotation = c.getAnnotation(Suite.SuiteClasses.class);

is null...

I know class loaders in server environment is different than that in pure JVM, but given the class already loaded(not null, no CNF) and I verified methods names can be printed, I would assume the class loaders aren't the ones causing this issue....





Aucun commentaire:

Enregistrer un commentaire