You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spring依赖注入运行TestNG测试时出现ClassFormatException报错

解决AspectJ与Allure StepsAspects的ClassFormatException问题

这个错误我之前在整合Allure和AspectJ的时候也踩过坑,核心原因是旧版AspectJ的BCEL组件无法解析Java 9及以上版本字节码里的新常量池标签(错误里的18对应Java 9引入的CONSTANT_MethodHandle相关常量),而Allure的StepsAspects类是用高版本JDK编译的,导致旧AspectJ处理不了字节码结构。

下面是几个经过验证的解决步骤:

1. 升级AspectJ到支持高JDK的版本

AspectJ 1.8.x及更早的版本自带的BCEL库不支持Java 9+的字节码常量,必须升级到1.9.x及以上版本。建议用最新的稳定版,比如1.9.20:

Maven依赖配置

<!-- 升级AspectJ核心依赖 -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.20</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.20</version>
    <scope>test</scope>
</dependency>

Gradle依赖配置

testImplementation 'org.aspectj:aspectjrt:1.9.20'
testImplementation 'org.aspectj:aspectjweaver:1.9.20'

2. 确保Allure依赖与AspectJ版本兼容

Allure 2.x系列的aspects组件需要配合AspectJ 1.9+使用,所以要同步升级Allure TestNG的版本到兼容的稳定版(比如2.24.0),避免版本冲突:

Maven示例

<dependency>
    <groupId>io.qameta.allure</groupId>
    <artifactId>allure-testng</artifactId>
    <version>2.24.0</version>
    <scope>test</scope>
</dependency>

3. 排除冲突的旧版BCEL依赖

有时候项目中其他依赖会引入旧版的BCEL库,和AspectJ自带的BCEL冲突。可以在依赖中显式排除旧版BCEL:

Maven排除示例

<dependency>
    <groupId>io.qameta.allure</groupId>
    <artifactId>allure-testng</artifactId>
    <version>2.24.0</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectj-bcel</artifactId>
        </exclusion>
    </exclusions>
</dependency>

4. 统一编译与运行的JDK版本

确保项目编译使用的JDK版本和运行TestNG测试的JDK版本一致,不要出现用JDK 11编译但用JDK 8运行的情况,否则也会导致字节码解析异常。可以在Maven的pom.xml中指定:

<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

5. 调整AspectJ加载时织入(LTW)配置

如果你的项目使用了AspectJ的加载时织入(比如通过aop.xml配置),确保没有不必要的织入规则覆盖Allure的aspects。不过更推荐优先通过版本升级解决,而不是修改织入规则,因为Allure需要StepsAspects来生成测试步骤报告。


内容的提问来源于stack exchange,提问作者infojolt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:52:36