11 Java Functions - biswajitsundara/Karate GitHub Wiki

We can store the java methods in an external file and then call them in our feature file. This is really helpful to manipulate the data. E.g if we want to pass on the current date in API request or if we want to parse the response and then validate etc.

Feature file

\src\test\java\tests\java\JavaTest.feature

Feature: Java Functions Demo

  Background: 
    * def javafn = Java.type('tests.java.JavaMethods')

  Scenario: Call Java Non Static Method
    * def result = new javafn().nonStaticMethod()

  Scenario: Call Parameterized Java Method
    * def result1 = new javafn().parameterizedMethod('World')
    * print result1
    
  Scenario: Call Parameterized Static Java Method
    * def result2 = javafn.parameterizedStaticMethod("Karate")
    And match result2 == 'HelloKarate'  
    
    
   Scenario: Write to external file
    * def result3 = javafn.writeData("Response")

External Java File

\src\test\java\tests\java\JavaMethods.feature

package tests.java;
import java.io.PrintWriter;

public class JavaMethods {
	
	public void nonStaticMethod() {
		System.out.println("Hello");
	}
	
	public String parameterizedMethod(String arg) {
		return "Hello"+arg;
	}
	
	public static String parameterizedStaticMethod(String arg) {
		return "Hello"+arg;
	}
	
	public static void writeData(String arg) {
		PrintWriter writer = null;;
		try {
			writer = new PrintWriter("data.txt","UTF-8");
			writer.println(arg);
			writer.close();
		}
		catch(Exception e){
			System.out.println(e.getMessage());
			writer.close();
		}
		
	}
}

Runner File

\src\test\java\tests\java\JavaTestRunner.java

package tests.java;
import org.junit.runner.RunWith;
import com.intuit.karate.junit4.Karate;

@RunWith(Karate.class)
public class BasicTestRunner {

}

Notes

  • First access the file and store it in a variable * def javafn = Java.type('tests.java.JavaMethods')
  • The format is Java.type(package.filename). Please note, the file extension is not included.
  • If we are accessing non static method then we will have to use new keyword. * def result = new javafn().nonStaticMethod()
  • For accessing static methods we can simply call the method. * def result2 = javafn.parameterizedStaticMethod("Karate")
⚠️ **GitHub.com Fallback** ⚠️