Home > Enterprise >  How to Call the Karate Scenario from the Java Programatically?
How to Call the Karate Scenario from the Java Programatically?

Time:11-27

I have Karate scenario defined as below

Feature: Random Users

  Background: 
    * url 'https://askuser.me'

  @get-user
  Scenario: Get Random User data
    Given path 'api'
    When method get
    Then status 200
    * string json = response
    * def Util = Java.type('com.example.mobiletest.utils.TestUtils')
    * def SaveResponse = Util.writeToJSONFile(json,'randomuser.json')

And is Corresponding Runner class defined as below:

public class RandomUserRunner {
    @Karate.Test
    public Karate testRandomUserRunner(){
        return Karate.run("RandomUser").relativeTo(getClass());
    }
}

I want to execute testRandomUSerRunner() programatically from other java function, how do I do that (reason this is, karate scenario fetches response and saves in json file, other method in java want to reuses these steps)

I tried to call as below but it didnt work:

RandomUserRunner runner = new RandomUserRunner();
runner.testRandomUserRunner();

Anyhelp or pointers would be really appreciated.

CodePudding user response:

First - a disclaimer. Karate is not designed for this. It looks like you are already using some Java utils from Karate, so I personally think trying to call Karate from Java is wrong. The JUnit classes exist to take care of reporting, and here also - the parallel Runner is recommended: https://stackoverflow.com/a/65578167/143475

That said, see if the Runner.runFeature() API meets your use case. You will be able to access variables created by the Feature also.

Refer: https://github.com/karatelabs/karate#invoking-feature-files-using-the-java-api

  • Related