我有一个Spring Boot项目,该项目正在使用硒对不同应用程序进行自动化测试。项目的输出档案是一个JAR文件。我有以下代码来启动chrome浏览器。
static {
try {
Resource resource = null;
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains(IAutomationConstans.WINDOWS_OS_NAME)) {
resource = new ClassPathResource("chromedriver.exe");
} else if (osName.contains(IAutomationConstans.LINUX_OS_NAME)) {
resource = new ClassPathResource("chromedriver");
}
System.setProperty("webdriver.chrome.driver", resource.getFile().getPath());
ChromeOptions capabilities = new ChromeOptions();
webdriver = new ChromeDriver(capabilities);
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
} catch (Exception e) {
System.out.println("Not able to load Chrome web browser "+e.getMessage());
}
}
除此以外,我在下面的Spring Boot代码中执行自动化代码。
@SpringBootApplication
@ComponentScan("com.test.automation")
@PropertySource(ignoreResourceNotFound = false, value = "classpath:application.properties")
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class TestAutomation{
public static void main(String[] args) {
System.out.println("&&&&&&&&&&&&&&&&&&&&&");
SpringApplication.run(TestAutomation.class, args);
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%");
}
}
我将chromedriver.exe放在src \ main \ resources下。如果我通过右键单击从eclipse中执行TestAutomation类,则一切工作正常。
但是,如果我通过mvn package命令生成jar文件并执行JAR文件,则会收到错误消息。
Not able to load Chrome web browser class path resource [chromedriver.exe] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/C:/user/automation/target/automationapp-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/chromedriver.exe
答案 0 :(得分:0)
尝试使用ResourceLoader;
@Autowired
ResourceLoader resourceLoader;
...
Resource resource = resourceLoader.getResource("classpath:chromedriver.exe")
...
答案 1 :(得分:0)
resource.getFile()期望资源本身在文件系统上可用,即,不能嵌套在jar文件中。在这种情况下,resource.getInputStream()将起作用。您需要修改代码,因为如果您尝试使用org.springframework.core.io.Resource加载资源并将其打包在jar中,则代码System.setProperty("webdriver.chrome.driver", resource.getFile().getPath());
的这一行将不起作用。