Kotlin: The Test Automation Sweetspot
Test automation is a very helpful technique to have in your test arsenal, not to mention the demand for this skill has been constantly raising these past few years due to the effects of Agile and DevOps practices, where in a best case scenario, you need your tests to detect errors early, fast and often.
There are many tools in various programming languages that can help you translate your scenarios to automated tests quick and easy across every layer, this is particularly important for test engineers since they are regularly mostly responsible for automating tests above the integration phase.
The programming language
In a typical software team, test automation responsibilities are sometimes split by using the test pyramid as a reference and taking into account how close a role is to a specific layer:
Taking aside the Unit & Integration tests which if done, will most likely be written by the developers in the same language used to build the system, everything above this layers can potentially be written using a different language:
- API tests
- GUI
- Web (Desktop & Mobile)
- Mobile
This is both good and bad. Good because it allows any team member to contribute in the language he is most proficient, bad because it can lead to library spaghetti.
The language is one of the many important things to consider before selecting a tool or library and should not be a thing of a hype.
The tooling
Before we choose a specific tool, we should take some time to research and back up that decision before going blindly into the night, I have seen projects fail just because someone decided to use a niche tool or language or because JS gave birth to a new framework that’s momentarily taking over the world.
So our research takes us to many tools in different languages, some of the most popular are:
- Java
- Ruby
- Python
- JavaScript
All of these are great languages each one with its pros and cons, but to find the one that allows us to create automated tests for the GUI (desktop & mobile, native mobile (Espresso & Appium) and API tests, we need to do some digging.
The ones that have the biggest offerings are Java and JavaScript, with their massive communities and libraries.
But, even though libraries are part of our investigation they are not part of our acceptance criteria, we are not searching for tools, we are searching for the best coverage/effort ratio in an ever changing landscape of tools so we don’t end up with API tests using a python library, using Selenium WebDriver with JavaScript, and Appium with Ruby for mobile…Yes, It happens.
And while we can leverage some of these tools in parallel, we cab have at least (from an effort perspective) one common point to serve as denominator, and this point is the language.
What if, in this time and day, we could find only one that gives us the best ratio between coverage, amazing libraries, ease of use and platform support, wouldn’t that be a no-brainer? It would, so you should take some time to consider if this language already exists.
Kotlin
Kotlin brings a lot of very interesting and useful features, and you can find extensive information regarding the language with a simple Google search, but many of the articles you will find are always expressed from a mobile app or backend development point of view.
But since test automation can also be described as a development discipline, all the good things Kotlin brings for creating apps or backends, it’s applicable for test automation as well.
Some already well known Kotlin facts:
- Kotlin is an OSS statically typed programming language that targets the JVM, Android, JavaScript and Native.
- Kotlin has both object-oriented and functional constructs.
- It’s arguably, easy lo learn.
- Is a Google first-class Android programming language among Java and C++ which has boosted its adoption and keeps growing every day. This means you will get support pretty easily, not to mention new articles every day regarding uses you can do with the language.
- It’s from JetBrains, so you have constant support and one of (or) the best IDE on the market in IntelliJ.
- Kotlin is 100% interoperable with the Java programming language. And this one is very important, because you tap into the JVM life force.
This life force means that you have at your disposal a great amount of libraries that you can use without extra effort and without the verbosity and grandeur of Java.
Yes, we could use Java for these libraries as well, but you wouldn’t be reading this post if you weren’t looking for an alternative.
Kotlin for automated tests development
There are many good uses you could make of Kotlin for creating automated tests, whether is for web with Selenium, API’s with Rest-Assured or mobile with Espresso and Appium and many, many more.
But we need to unify the anecdote, not to speak on specific usages on a specific layer, but rather to summarize that you can use Kotlin for almost everything related to test automation development, period.
Let’s scratch the surface and see some of the things you can do with Kotlin.
As a starting point, it’s nice to note that you can write pretty readable names for your test functions, so you go from this:
public void testThatHangingOutWithRickAndMortyIsNotAGoodIdea(){
//code
}
To this:
fun `test that hanging out with Rick and Morty is not a good idea`(){
//code
}
Another excellent feature about this language it’s the abilty to create a DSL, which give us clarity and easy understanding and still just code:
fun `should login successfully`() {
withLoginRobot {
initiateTheLogin()
} and {
acceptThePermissions()
} andThenVerifyThat {
userIsLoggedIn()
}
}
Or:
val cities : List<String> =
Given {
queryParam("deleted", false)
} When {
get("/users")
} Then {
statusCode(200)
body("size()", is(3))
body("name.any { it == 'Ervin Howell' }", is(true))
body("find { user -> user.username == 'Antonette' }.company.name", equalTo("Romaguera-Jacobson"))
} Extract {
path("address.city")
}
With Kotlin you can also say more using less, you can reduce the size of your code while keeping the same or more functionality when compared to Java. The following example takes a POJO in Java for illustration purposes:
1 public class Person {
2 private String name;
3 private int age = 0;
4
5 public Person(String name, int age) {
6 this.name = name;
7 this.age = age;
8 }
9
10 public String getName() {
11 return name;
12 }
13
14 public void setName(String name) {
15 this.name = name;
16 }
17
18 public int getAge() {
19 return age;
20 }
21
22 public void setAge(int age) {
23 this.age = age;
24 }
25
26 @Override
27 public boolean equals(Object o) {
28 if (this == o) return true;
29 if (o == null || getClass() != o.getClass()) return false;
30
31 Person person = (Person) o;
32
33 if (name != null ? !name.equals(person.name) : person.name != null) return false;
34 if (age != 0 ? age != person.age : person.age != 0) return false;
35 }
36
37 @Override
38 public int hashCode() {
39 int result = name != null ? name.hashCode() : 0;
40 result = 31 * result + age;
41 return result;
42 }
43
44 @Override
45 public String toString() {
46 return "Person{" +
47 "name='" + name + '\'' +
48 ", age='" + age + '\'' +
49 '}';
50 }
51 }
This is basically the above code in Kotlin with 50 lines less:
1 data class Person(var name: String, var age: Int)
You can also add up the fact that today most of the Android native development is being done or migrated to Kotlin, so you can have a very good source of help and support right there in your team.
Hidden perks
And here is an unnoticed perk of using Kotlin, it’s that you can learn and transition to Swift with very little effort, they are very similar:
println("Hello, world!")
print("Hello, world!")
fun makeIncrementer(): (Int) -> Int {
val addOne = fun(number: Int): Int {
return 1 + number
}
return addOne
}
val increment = makeIncrementer()
increment(7)
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
let increment = makeIncrementer()
increment(7)
You can find the above and many more similarities here
Why is this important: let’s say that you got a hang of Espresso, and you want to do the same on IOS, meaning start converting some IOS Appium scripts that can fit in a layer below, for that you can use XCUITest, it’s like the Espresso of IOS.
Final Thoughts
I like to automate things, and in our work whatever commodity or optimization where I get the same or better results with less effort, I will at least try it. Since I started using Kotlin instead of Java for my test automation I haven’t looked back.
So if you are a tester or developer walking your first steps in writing automated tests or even if you are an experienced one, keep in mind that with Kotlin you can target almost every aspect of your test automation with much less effort.
In Kotlin you will find an easy, modern and fun language that will be a powerful ally for your testing purposes.
Go ahead and give it a try, let me know how it goes.