简体   繁体   English

如何对返回null的getClassLoader()进行单元测试

[英]How to unit test getClassLoader() returning null

As per the javadoc of Class 根据的javadoc

Returns the class loader for the class. 返回该类的类加载器。 Some implementations may use null to represent the bootstrap class loader. 一些实现可能使用null来表示引导类加载器。

We have to unit test the logic when getClassLoader returns null. 当getClassLoader返回null时,我们必须对逻辑进行单元测试。 We are using sun implementation of Java (Java 6). 我们正在使用Java(Java 6)的sun实现。 How can we do this. 我们应该怎么做。

My first thought, was just mock the Class object but as mentioned in this other question : Mocking a class object using Mockito and PowerMockito 我的第一个想法只是模拟Class对象,但是在另一个问题中提到: 使用Mockito和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. Mockito,Easymock(和Powermock)之类的模拟对象库无法模拟由引导类加载器加载的类,因为在加载模拟对象库时它们已经被加载了。 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 in java.lang , java.net , java.io ). 因此,一个简单的解决方法是查看是否可以使用由引导程序类加载器加载的类,例如java.langjava.netjava.io类。

For example String.class.getClassloader() will return null . 例如String.class.getClassloader()将返回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. 如果您不能轻松地使用自举类进行测试,那么我将不必为该分支担心太多,因为它将无法在生产中执行。

Put the target class into its own JAR, and then launch the test JVM with -Xbootclasspath/a:testclass.jar . 将目标类放入其自己的JAR中,然后使用-Xbootclasspath/a:testclass.jar启动测试JVM。 This will cause all classes in that JAR to be loaded by the boot class loader. 这将导致引导类加载器加载该JAR中的所有类。 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) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM