Here is described how to setup Selenium for a SpringBoot maven-project.
Add following dependency to projects pom.xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
<scope>test</scope>
</dependency>
Chromedriver has to be executable. Unfortunatly file-mod is lost when maven copy resources to target directory. This can be fixed by adding following snippet to the build section in pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>set-webdriver-filemod</id>
<phase>process-test-classes</phase>
<configuration>
<target>
<chmod file="target/test-classes/chromedriver" perm="755"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
To reduce setup effort for other project members, we'll add ChromeDriver as test resource to the project.
Download latest chromedriver from here: https://sites.google.com/a/chromium.org/chromedriver/
Copy it to src/test/resources
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FrontendTest {
private static final String DRIVER_NAME = "chromedriver";
@Value("${local.server.port}")
private int port;
private WebDriver webDriver;
@Before
public void initWebDriver() throws IOException {
String driverPath = this.getClass().getClassLoader().getResource(DRIVER_NAME).getPath();
System.setProperty("webdriver.chrome.driver", driverPath);
webDriver = new ChromeDriver();
}
@After
public void quitDriver() {
if (webDriver == null) {
return;
}
webDriver.quit();
}
@Test
public void pageTitle() {
String url = String.format("localhost:%s", port);
webDriver.navigate().to(url);
System.out.println(webDriver.getTitle());
}
}
To run this test on a jenkins, just install chromium-browser on the build server. Othewise following exception will occur:
org.openqa.selenium.WebDriverException: unknown error: cannot find Chrome binary