Defining and calling Java functions
Even though JavaScript offers a lot of functionality, sometimes it can be easier to use Java for specific tasks. Fortunately, Karate can call and use Java classes and methods within JavaScript, as mentioned in Chapter 1, Karate’s Core Concepts.
Understanding the basics
First, let’s see how to use Java classes that are part of Java itself to slowly start exploring this powerful feature. For this example, I want to determine the current directory of our running test. There are, of course, many ways to do this, both in JavaScript and Java. Here, I will use the java.nio.file.Paths
class that is built into Java to accomplish this.
This would be the pure Java statement:
String currentPath = Paths.get(".").toAbsolutePath().toString();
Basically, this gets a Path
instance of "."
(which stands for the current path) and then returns the full path of this using the toAbsolutePath()
method...