Selenium + Kotlin = šŸ˜„

Brian Grogan Jr.
Qualitas Ex Machina
2 min readMay 31, 2020
Kotlin + Selenium

Iā€™ve been arguing against using Java for test automation code for years. Java is too verbose and its edit-compile-run cycle is too slow to be effective for an automation project.

One response I get back is that someoneā€™s team is so heavily invested in the JVM ecosystem, itā€™s just not realistic to leave it behind to move to a different language. And alternative JVM languages like Scala, while very interesting, are not the best fit for automation code.

Another alternative, Kotlin, gained a lot of attention last year after Google made it the new standard for Android app development. Kotlin has also developed into a really compelling choice for test automation code. Hereā€™s an example of what that looks like:

Imports

The import statements for a typical test all look the same as usual, except you donā€™t need to remember to end lines with semi-colons anymore. You can import all your usual testing libraries like JUnit, TestNG, Hamcrest, AssertJ, and Selenium, with no extra steps.

Test Class

The test class follows all the typical patterns: annotate the class with @RunWith, and define setUp and tearDown methods with @Before and @After where you instantiate the WebDriver, and then quit it. There are only a few Kotlin-specific changes here. The lateinit modifier signals that the driver object will be instantiated outside of the constructor method. The data class gives us a quick way to define a simple class for holding some values.

Test Method

In the test method, there are more noticeable differences, but you can see some of the benefits of using Kotlin too.

Test method names can use the backtick syntax to put spaces between the words of the names. Local values inside the method that would normally be assigned to variables, are assigned to immutable values instead, to prevent accidentally changed variables. Kotlinā€™s type inference allows you to omit all of the type names on the left side of assignments.

Otherwise, the interactions with the Selenium library all look re-assuringly familiar.

Something Old, Something New

Kotlin makes it possible to write more concise and expressive code, while using the same libraries and the same platform that you would use in a Java-based project. I hope these examples inspire you to give Kotlin a try.

And for reference, hereā€™s the full code sample:

Complete Example

--

--

Brian Grogan Jr.
Qualitas Ex Machina

Software Quality Engineer fighting for truth, justice, and better quality apps. Thinks a lot about Automation and CI/CD, in both practical and abstract terms.