java class
public class Utilities {
public static String generateRandomString(int length) {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = (int) (Math.random() * chars.length());
sb.append(chars.charAt(index));
}
return sb.toString();
}
}
Feature file
Background:
* def RandomStringGenerator = Java.type('Utilities')
* def randomString = callonce RandomStringGenerator.generateRandomString(10)
* print 'a'+randomString
Scenario: Use Random String
* print 'b'+randomString
Scenario: Use Random String in scenario2
* print 'c'+randomString
The randomString is printing null instead of the string generated. i am using karate 0.9.5 version if that helps
Call the static Java method via JavaScript. You have missed to add package name of the java class Utilities. Replace the feature file like below.
Feature: call java static method
Background:
* def generateData =
"""
function(arg) {
var JavaDemo = Java.type('com.tests.Utilities');
return JavaDemo.generateRandomString(arg);
}
"""
* def result = callonce generateData 10
* print 'a'+result
Scenario: Use same string value scenario1
* print 'b'+result
Scenario: Use same string value scenario2
* print 'c'+result
Official Karate Doc: https://github.com/karatelabs/karate#calling-java