1

As per KARATE documentatoion we should use System.setProperty() to set env in test case level, But that option is not working in karate 1.2.0 (Didn't verify in previous versions)

Feature


Feature: Testing env changing
  Scenario: Reading base url of different env
  * print 'Before changing env...---> '+ karate.env
  * print 'Testing karate...'
  * print baseUrl
  * java.lang.System.setProperty("karate.env","STAGE")
  * def newevn = java.lang.System.getProperty('karate.env')
  * print 'After changing env...---> '+ newevn
  * def fun = call read('file:karate-config.js') 
  * print 'Changed env...---> '+ fun.baseUrl

Karate-Config.js file-

function fn() {
  karate.configure('connectTimeout', 5000);
  karate.configure('readTimeout', 5000);
  var env = karate.env;
  karate.log('karate.env system property was:', env);

  var baseUrl = 'testingbase.com';
  karate.log('Env---->' + env)
  var port = karate.properties['demo.server.port'] || '8080';
  var protocol = 'http';

  var config = {
    env: env,
    baseUrl: 'https://localapi.abc123.example.com/api/v1/validate/customerid',
    apiKey: ''
  }
  if (karate.properties['demo.server.https'] === 'true') {
    protocol = 'https';
    karate.configure('ssl', true);
  }
  var config = { demoBaseUrl: protocol + '://127.0.0.1:' + port };
  if (env== 'mock') {
    // karate.configure('callSingleCache', { minutes: 1 });
    // 'callSingle' is guaranteed to run only once even across all threads
    //var result = karate.callSingle('classpath:demo/headers/common-noheaders.feature', config);
    // and it sets a variable called 'authInfo' used in headers-single.feature
   // config.authInfo = { authTime: result.time, authToken: result.token };
  }
  else if(env=='BETA'){
 config.baseUrl='tetsing.beta.base.com';

  }
  else if(env=='STAGE'){
config.baseUrl='tetsing.stage.base.com';

  }
  return config;
}

SMJ
  • 13
  • 3

1 Answers1

0

Please note that you can't call java.lang.System.setProperty() within a feature and expect that to work. The environment is locked in at the time that karate-config.js is evaluated, which is before a Feature even executes.

Please read the docs: https://github.com/karatelabs/karate#switching-the-environment

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Is there any way to switch between env and hit request, Just to verify response between different environment. – SMJ May 16 '22 at 17:50
  • @ShridharaMJ just use the `Runner` API twice ? see: https://stackoverflow.com/a/72253684/143475 - otherwise maybe you over-engineered your tests and what you need is not 2 environments but a single test with 2 data-driven rows: https://stackoverflow.com/a/69092767/143475 – Peter Thomas May 16 '22 at 18:35