Gatling Scala命令行运行报错:找不到或无法加载主类Engine
解决Gatling「Could not find or load main class Engine」错误
核心问题分析
你的问题根源在于:
- 打包命令未正确编译
src/test目录下的Scala代码(Engine等类位于test目录) - Assembly插件默认仅打包
src/main下的编译产物,未包含test类 - 擅自将
src/test移至src/main导致依赖范围冲突(Gatling依赖默认是testscope,移到main会缺失依赖)
分步解决方案
1. 恢复项目原始结构
将代码移回src/test目录,Gatling官方推荐测试代码放在test目录下,依赖会自动使用test scope,避免编译错误。
2. 修正POM.xml关键配置
配置Scala编译插件(确保编译test目录代码)
添加testCompile目标,编译src/test/scala下的所有类:
<plugin> <groupId>net.alchim31.maven</groupId> <artifactId>scala-maven-plugin</artifactId> <version>4.8.1</version> <executions> <execution> <id>compile-scala</id> <goals> <goal>compile</goal> <goal>testCompile</goal> <!-- 必须添加,编译test目录代码 --> </goals> <configuration> <scalaVersion>2.13.10</scalaVersion> <args> <arg>-deprecation</arg> <arg>-feature</arg> </args> </configuration> </execution> </executions> </plugin>
配置Assembly插件(包含test类并指定主类)
修改Assembly插件配置,确保包含test-classes并指定Engine类的全限定名:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.4.2</version> <executions> <execution> <id>build-fat-jar</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <archive> <manifest> <!-- 替换为你的Engine类全路径,比如无包则写Engine,有包则写testrunner.Engine --> <mainClass>Engine</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <includeTestResources>true</includeTestResources> <appendAssemblyId>false</appendAssemblyId> <!-- 显式引入Gatling测试依赖 --> <dependencies> <dependency> <groupId>io.gatling</groupId> <artifactId>gatling-app</artifactId> <version>3.9.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.gatling</groupId> <artifactId>gatling-core</artifactId> <version>3.9.0</version> <scope>test</scope> </dependency> </dependencies> </configuration> </execution> </executions> </plugin>
3. 使用正确的打包命令
执行以下命令编译test代码并打包:
mvn clean test-compile assembly:single
4. 验证打包结果
用以下命令检查jar包是否包含Engine类:
jar tf your-jar-name.jar | grep Engine
如果输出Engine.class(或对应包路径下的类文件),说明打包成功,此时运行jar即可:
java -jar your-jar-name.jar
新手更优方案:使用Gatling官方Maven插件
无需手动打包,直接用官方插件运行仿真,更简单可靠:
- 在POM中添加Gatling插件:
<plugin> <groupId>io.gatling</groupId> <artifactId>gatling-maven-plugin</artifactId> <version>3.9.0</version> <configuration> <!-- 替换为你的仿真类全路径:testrunner.testsimuation1 --> <simulationClass>testrunner.testsimuation1</simulationClass> </configuration> </plugin>
- 直接运行仿真:
mvn gatling:test
额外排查点
- 确认
Engine类的全限定名:查看target/test-classes目录下的文件结构,比如类文件在target/test-classes/testrunner/Engine.class,则主类为testrunner.Engine - 检查Maven使用的JDK版本:执行
mvn -v,确保Java版本为1.8 - 确认Gatling与Scala版本兼容:Gatling 3.9.0支持Scala 2.13.x,你的版本匹配无问题
内容的提问来源于stack exchange,提问作者perf_tester
相关产品推荐
相关产品推荐

