Search code examples
javatestingmockingcucumberkarate

Karate mock with @setup scenario does not work


I'm on karate v1.4.0

Want to define a function and a variable to be used on mock creation (pathToMy.js always returns true):

@setup
Scenario:
    * def data = read('data.json')
    * def myFunc = read('pathToMy.js')

Scenario: pathMatches('/my_url') && methodIs('post') && myFunc()
    * def responseHeaders = { 'Content-Type': 'application/json' }
    * def response = data
    * def responseStatus = 200

When I request to /my_url on test run, it does not return anything: moreover, just having another scenario with or without @setup does not allow mock URL to be captured:

Scenario:
    * def data= read('data.json')

# Note that not connected to the above scenario at all
Scenario: pathMatches('/my_url') && methodIs('post') 
    * def responseHeaders = { 'Content-Type': 'application/json' }
    * def response = {"my":"data"} 
    * def responseStatus = 200

Also, when not using additional scenario, but trying to call the method to match, it does not work:

Scenario: pathMatches('/my_url') && methodIs('post') && call read('pathToMy.js') # call diectly
    * def responseHeaders = { 'Content-Type': 'application/json' }
    * def response = {"my":"data"}
    * def responseStatus = 200

But when I do the same thing without additional scenario and method call it works:

Scenario: pathMatches('/my_url') && methodIs('post') 
    * def responseHeaders = { 'Content-Type': 'application/json' }
    * def response = read('data.json') # read data from a file
    * def responseStatus = 200

P.S. An ideal solution for my use case would be a possibility to have Scenario Outline, but seems it is also not supported (as I use @setup to provide an external json file)


Solution

  • The @setup hook is designed to work only for tests and not for mocks. Since the Background for mocks is run "once only", you just set a variable, call a JS function if needed and nothing more is required. If you do need something specific, do consider contributing code.