End-to-end testing with Selenium, Gradle, JUnit
I wanted to test a web page using JVM, but there are scattered tutorials everywhere. I decided to create a barebones project to illustrate how.
Our goal will be to test the end-to-end flow of adding a Kindle to the cart on Amazon.com.
1. New project
Follow the steps at:
Kotlin/Gradle/JUnit starter project
Just a quick tutorial to start a black new Kotlin project using Gradle and Junit.
Add Selenium to the dependencies:
TestAmazonCart and paste the following basic test that visits Amazon:
This assumes you have Chrome, but you can replace
chromedriver() with other.
3. Page object model
Let’s create the following files:
Some people like to put all the selectors in the beginning, but I avoid that due to simplicity and because they're used only once.
How about a beautiful report? Just add the Allure report dependency to
id("io.qameta.allure") version "2.9.6"
id("io.qameta.allure-report") version "2.9.6"
Run the tests. Then, to view its report, run:
How about adding screenshots to the report when a test fails? Create the following utility:
Now, you just need to inject it into the test:
private val screenshotOnError = ScreenshotOnError(driver as RemoteWebDriver)
This is enough to add the screenshot to the Allure report.
If you need to integrate this into your CI/CD system, you need to use a headless browser (browser runs without UI). For that, you can change the setup to:
private val driver = ChromeDriver(ChromeOptions().addArguments("--headless"))
private val screenshotOnError = ScreenshotOnError(driver)
Be aware that the
addArguments part needs to depend on an environment variable so that you can run on headless only on CI/CD and not on local testing.