Karate Java String interpolation

Viewed 70

I am trying to call a java method that accepts a string as a parameter inside a karate script, and interpolate a value defined in karate in that string.

In my case it's a simple database INSERT statement, for example:

INSERT INTO A(id, time, value) VALUES(1, '2099-05-10 18:20:18.674 UTC', 'test')

The script itself looks as follows:

Background:
    * def db = Java.type('com.example.DbTestHelper')
    * def offsetDateTime = Java.type('java.time.OffsetDateTime')
    * def zoneId = Java.type('java.time.ZoneId')

  Scenario: testScenario
    * def t = offsetDateTime.now(zoneId.of("Europe/Berlin")).plusDays(1)
    * def row = db.insertRow("INSERT INTO A(id, time, value) VALUES(123, #t, 'test')")

And the insertRow method looks as follows:

    @JvmStatic
    fun insertRow(vararg strings: String) {
        jdbc.batchUpdate(*strings)
    }

I have tried multiple combinations of setting value t like #(t), #t, "#(t)" etc. Unfortunately, none of them worked resulting in various javascript parse errors even before the java method gets invoked.

What would be the right way to achieve that? Is it even possible?

1 Answers

First read this: https://github.com/karatelabs/karate#rules-for-embedded-expressions

The good news is that in 1.0 onwards Karate supports ES6 JS string interpolation within backticks:

* def foo = 1
* def txt = `hello ${foo}`
* match txt == 'hello 1'

Of course string concatenation will always work. You just have to think of most Karate syntax especially when you call Java - as being nothing but plain old JavaScript.

* db.insertRow("INSERT INTO A(id, time, value) VALUES(123, " + t + ", 'test')")

I think you will be able to proceed now.

Related