I'm having problems running a JUnit test.
It runs fine in Eclipse, but now I'm trying to run it from the command-line using Ant. The problem is that the following code is returning null: getClass().getPackage()
.
I'm running my JUnit test like so:
<junit fork="no" printsummary="yes" haltonfailure="no">
<classpath refid="junit.classpath" />
<batchtest fork="yes" todir="${reports.junit}">
<fileset dir="${junit.classdir}">
<include name="**/FileHttpServerTest.class" />
<exclude name="**/*$*" />
</fileset>
</batchtest>
<formatter type="xml" />
...
I Googled for this sort of error, and f开发者_运维百科ound a number of references to classloader misbehaviour. But I've found nothing gave me enough information to solve my problem.
I really need getClass().getPackage()
to not return null. Can anyone help me?
Thanks, Phil
I am not sure on which object are you trying to do getClass().getPackage()? Looking at what the API Javadoc says for this method, I would guess that the issue is JUnit is being loaded by Bootstrap classloader when you are running it from command line whereas the object on which you are doing getPackage() operation is loaded by one of the child classloaders.
Not sure if this makes sense, but because getPackage is trying to locate the package using Bootstrap classloader and standard class loader behavior does not look at its children, it returns null.
If you can give more idea about the object on which you are doing this operation, I could be more specific
Try running your tests with junit fork="yes"
, that will isolate your classloading pretty reasonably and may fix your problem.
If it's a classloader's fault, you can always load the same class using different classloader:
URLClassLoader cld = new URLClassLoader(new URL[] { urlsToClasses });
Class.forName(getClass().getName(), true, cld).getPackage();
The problem here is to figure out, how to find class path urls (urlsToClasses
). I'm not familiar with JUnit classloaders, so you may try to cast Thread.currentThread().getContextClassLoader()
to URLClassLoader
to see if it could help you obtain that URLs.
精彩评论