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.
Official Karate Doc: https://github.com/karatelabs/karate#calling-java