Luca Pelosi
Luca Pelosi

Reputation: 158

Select mock file to use based on the running Karate Scenario

I'm using Karate 1.4.0

I have some Karate Scenarios to test my application and I'm using a Karate MockServer as mocked downstream service.

To simulate edge case scenarios (e.g. empty results from downstream), I want to select a specific mock file based on the running Karate Scenario. Is there a way to know which is the Scenario that triggered the downstream mock call?

// myScenarios.feature
Scenario: scenario 123
  ...


// myDownstreamMock.feature
Scenario: pathMatches('/downstream/path/api/v0')
  ...
  def responseStatus = 200
  string mockFileName = "<NAME_BASED_ON_MY_SCENARIO_123>.json"
  def response = read (mockFileName)

At the moment the only workaround I found is to pass this information into some fields I know are propagated to the downstream (e.g. custom headers) so that I can retrieve that field in mock feature and select the proper mock file.

For example:

// myScenarios.feature
Scenario: scenario 123
  ...
  And headers {'test-id': 'scenario123'}
  When method post
  ...


// myDownstreamMock.feature

Scenario: pathMatches('/downstream/path/api/v0')
  ...
  string mockFileName = requestHeaders['test-id'] + ".json"
  def response = read (mockFileName)

This cannot work with all downstream so I need to find a better way.

Upvotes: 1

Views: 63

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

You can see if the API karate.scenario gets you what you need. It will return a JSON of metadata about the currently executing Scenario. I really don't remember if it works for mocks though. If it doesn't, it may need some code contributions.

Upvotes: -1

Related Questions