1

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?
    }
}
hueller
  • 314
  • 2
  • 9

2 Answers2

-1

if you need to call external javascript functions from java code I suggest you take a look at this

gazzo
  • 314
  • 3
  • 12
-1

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.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • My Junit test class looks pretty much like https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/DemoTestParallel.java . I would like to extend the Cucumber HTML report with some additional information (e.g. environment, ...), which I would like to read out of the karate-config.js . – hueller May 09 '19 at 15:14
  • @altes-kind that doesn't answer my question. anyway I provided a working solution (I think). as the dev of karate I do highly suspect you are doing things that are best done in Karate (and not Java). just my 2 c – Peter Thomas May 09 '19 at 15:16
  • Thanks for your help! My first comment was accidentally submitted without containing the full text. Maybe you can read it again to understand why I would like to access the config from within a JUnit test? I'll try the workaround using the empty scenario - even though it feels a bit ugly. – hueller May 09 '19 at 15:22
  • 1
    @altes-kind looks like you edited your comment. okay, here's my suggestion. set some Java system properties from the `karate-config.js` and read them before the cucumber report routine, problem solved – Peter Thomas May 09 '19 at 15:22