我正在开发一个 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 为测试环境加载对象,Sun 使用他的 AppClassLoader 加载相同的对象。由于类加载器不同,因此在运行时对象也是(除了它们具有相同的名称),这意味着 LinkageError。
无论如何,我尝试了几种方法来避免这种情况,例如通过删除 expectedExceptions 标记并添加 try 和 catch 子句,但没有成功。
如何为该异常设置一个唯一的类加载器?这是解决它的正确方法吗?还是我应该尝试别的东西?我的 Maven 配置可能有问题吗?欢迎任何想法或意见:)