我正在开发一个Maven项目,我正在尝试使用以下结构执行TestNG单元测试:
import org.testng.*;
@PrepareForTest(GeneralDAO.class)
@PowerMockIgnore({"javax.management.*"})
public class TestClass extends PowerMockTestCase {
@Test(expectedExceptions = BusinessException.class) // custom exception from another project
public void testFailToGetBusiness() {
// method that shoud throw a BusinessException
}
}
但是当我运行测试时,我发现以下异常:
java.lang.LinkageError: loader constraint violation: when resolving method "com.company.exception.BusinessException.<init>(Ljava/lang/Exception;Lcom/company/exception/EExceptionCodes;)V"
the class loader (instance of org/powermock/core/classloader/MockClassLoader)
of the current class, com/company/core/BusinessHandler,
and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, com/company/exception/BusinessException,
have different Class objects for the type com/company/exception/EExceptionCodes used in the signature
据我所知,powermock使用MockClassLoader为测试环境加载Object,而Sun使用他的AppClassLoader加载相同的Object。由于类加载器不同,在运行时对象也是(除了它们具有相同的名称),这意味着LinkageError。
无论如何,我已经尝试了几种方法来避免这种情况,例如删除expectedExceptions标记并添加try和catch子句,但没有成功。
如何为该异常设置唯一的类加载器?这是解决它的正确方法吗?或者我应该尝试别的东西?可能是我的Maven配置出了问题?欢迎提出任何想法或意见:)