Skip to content
Advertisement

How to access Karate config parameters in JUnit tests?

Is there a way to access the config parameters from karate-config.js within JUnit tests?

Example:

karate-config.js

function fn() {   
  var env = karate.env; // get java system property 'karate.env'
  karate.log('karate.env system property was:', env);
  if (!env) {
    env = 'dev'; // a custom 'intelligent' default
  }
  var config = { // base config JSON
    appId: 'my.app.id',
    appSecret: 'my.secret',
    someUrlBase: 'https://some-host.com/v1/auth/',
    anotherUrlBase: 'https://another-host.com/v1/'
  };
  if (env == 'stage') {
    // over-ride only those that need to be
    config.someUrlBase = 'https://stage-host/v1/auth';
  } else if (env == 'e2e') {
    config.someUrlBase = 'https://e2e-host/v1/auth';
  }
  // don't waste time waiting for a connection or if servers don't respond within 5 seconds
  karate.configure('connectTimeout', 5000);
  karate.configure('readTimeout', 5000);
  return config;
}

MyTest.java

public class MyTest {

    @Test
    public void test() {
        // How to access e.g. config.appId?
    }
}

Advertisement

Answer

But why !?

There are multiple ways, but first – maybe you are over-engineering things and note that it is possible to read a *.properties file in Karate: properties.feature

You can also create a feature file with a single, empty Scenario – and call it from the Java API: https://github.com/intuit/karate#java-api

Map<String, Object> result = Runner.runFeature('classpath:foo.feature', null, true);

Which will give you the values of config in the returned Map.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement