能否借助Eclipse IDE实现Selenium Java+Cucumber脚本每日无人值守自动运行?
实现Selenium+Cucumber Java脚本每日无人值守自动运行方案
1. 将项目打包为可执行JAR包
先脱离Eclipse IDE,把测试项目打包成能独立运行的JAR包,推荐用Maven管理依赖和打包:
- 若项目未配置Maven,先添加Maven支持,在
pom.xml中引入Cucumber、Selenium及相关依赖,同时配置maven-shade-plugin或maven-assembly-plugin,打包包含所有依赖的可执行JAR。 - 也可直接在Eclipse导出Runnable JAR:右键项目→Export→Runnable JAR File,选择自定义的测试启动类(若没有,可编写调用Cucumber API的主类,示例如下):
import io.cucumber.core.cli.Main; public class TestRunner { public static void main(String[] args) { Main.run(new String[]{ "--glue", "com.your.package.stepdefs", "src/test/resources/features", "--plugin", "html:target/cucumber-report.html" }, Thread.currentThread().getContextClassLoader()); } }
打包时选择该TestRunner作为启动类,勾选"Package required libraries into generated JAR",生成可执行JAR文件。
2. 编写运行脚本
根据操作系统编写对应的执行脚本:
- Windows批处理(.bat):创建
run-tests.bat文件,内容如下:
@echo off java -jar "D:\path\to\your\test-jar.jar" >> "D:\path\to\logs\test-run-%date:~0,4%%date:~5,2%%date:~8,2%.log" 2>&1
- Linux/macOS Shell脚本(.sh):创建
run-tests.sh,内容如下:
#!/bin/bash java -jar /path/to/your/test-jar.jar >> /path/to/logs/test-run-$(date +%Y%m%d).log 2>&1
给Shell脚本添加执行权限:
chmod +x run-tests.sh
3. 配置无头模式(必做)
无人值守运行无图形界面,必须开启浏览器无头模式,否则会启动失败。以Chrome为例,修改Selenium驱动初始化代码:
ChromeOptions options = new ChromeOptions(); options.addArguments("--headless=new"); options.addArguments("--disable-gpu"); options.addArguments("--window-size=1920,1080"); WebDriver driver = new ChromeDriver(options);
4. 设置定时任务
配置系统定时任务,让脚本每日自动运行:
- Windows:打开「任务计划程序」→ 创建基本任务,设置触发时间为每日指定时刻,操作选择「启动程序」,选中你的
run-tests.bat文件,完成配置。 - Linux/macOS:终端执行
crontab -e,添加定时规则,比如每天9点执行:
0 9 * * * /path/to/run-tests.sh
保存退出后,crontab会自动加载该定时任务。
内容的提问来源于stack exchange,提问作者Tata pramod
相关产品推荐
相关产品推荐

