我正在尝试针对一个角度应用程序创建Selenium测试。我希望这些测试在我的持续集成构建中运行,这就需要以无头模式运行它们。我想用无头铬合金。
head
和
body
标签。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleSeleniumTest {
@LocalServerPort
private int port;
@Autowired
private WebDriver driver;
@Test // Always works
public void testGoogle() {
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!");
element.submit();
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
for (WebElement webElement : findElements) {
System.out.println(webElement.getAttribute("href"));
}
Assert.assertTrue(findElements.size > 0);
}
@Test // Breaks in headless mode
public void testLocalAngular() {
driver.get("localhost:" + port);
String pageSource = driver.getPageSource();
// Page source empty in headless mode
System.out.println(pageSource);
String title = driver.findElement(By.className("mat-card-title")).getText();
Assert.assertEquals("My Starter", title);
}
}
这些测试取决于以下配置
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan(basePackageClasses = MyStarterApplication.class)
public class SeleniumConfig {
@Value("${selenium.headless:#{true}}")
private boolean headless;
@EventListener(classes = ApplicationReadyEvent.class)
public void prepareDriver() {
// Using https://github.com/bonigarcia/webdrivermanager
ChromeDriverManager.getInstance().setup();
}
@Bean(destroyMethod = "quit")
public WebDriver webDriver() {
ChromeOptions options = new ChromeOptions();
if (headless) {
options.addArguments("headless");
options.addArguments("window-size=1200x600");
}
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
return driver;
}
}