Reputation: 675
As per the javadoc of Class
Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader.
We have to unit test the logic when getClassLoader returns null. We are using sun implementation of Java (Java 6). How can we do this.
Upvotes: 1
Views: 1176
Reputation: 33946
Put the target class into its own JAR, and then launch the test JVM with -Xbootclasspath/a:testclass.jar
. This will cause all classes in that JAR to be loaded by the boot class loader. This will be trickier if the class needs to have other dependencies.
Alternatively, my approach in the past has been to refactor the code to add a special entry point for test purposes:
public void someMethod(Class c) {
someMethodImpl(c, c.getClassLoader());
}
// Exposed for test only.
void someMethodImpl(Class c, ClassLoader cl) {
...
}
Upvotes: 0
Reputation: 31648
My first thought, was just mock the Class object but as mentioned in this other question : Mocking a class object using Mockito and PowerMockito
you can't. Mock object libraries like Mockito, Easymock (and Powermock) can't mock classes loaded by the bootstrap class loader since they have already been loaded by the time the mock object library gets loaded. So it can't manipulate the bytecode.
So, an easy work around is to see if you can use a class that is loaded by the bootstrap class loader for example, classes injava.lang
, java.net
, java.io
).
For example String.class.getClassloader()
will return null
.
If you aren't able to easily use a bootstrapped class to make your test, then I wouldn't worry too much about that branch since it won't be able to get executed in production.
Upvotes: 1