1

Is there an easier way to call a Java assertion from a Karate test and provide the assertion a failure message? I have a feeling there must be a more elegant way?

Here is how I am INCORRECTLY doing it now:

* def assertNotBlank =
    """
    function(val, msg) {
      var Assertions = Java.type('org.junit.jupiter.api.Assertions');
      var StringUtils = Java.type('org.apache.commons.lang3.StringUtils');
      var JSONObject = Java.type('org.json.JSONObject');
      return Assertions.assertFalse(StringUtils.isBlank(
        new org.json.JSONObject(val).toString()), msg);
    }
    """

Then call it in your feature file like so:

And eval assertNotBlank {val: '#(response)', msg: 'The reason here.'}
djangofan
  • 28,471
  • 61
  • 196
  • 289

1 Answers1

0

Seeing this code makes me think you are better off not using Karate and just sticking to Java, especially when I see things like the new org.json.JSONObject. Karate is so good at handling JSON, why on earth would you want to do that ?

Also you probably mean call instead of eval.

That said, maybe this answer will give you some hints, read the comments as well: https://stackoverflow.com/a/60693949/143475

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • 1
    I guess I went down that path because I needed to have an assertion with a custom failure message on it. Is that possible out of the box? – djangofan Mar 19 '20 at 20:19
  • @djangofan no and I believe you don't need it. `match` failures do give you a built-in message. if you really need extra, just do a `print` on the line before. if you really really want, you can use a JS `throws` clause: https://github.com/intuit/karate#conditional-logic – Peter Thomas Mar 20 '20 at 01:38
  • Thanks, that is what I needed – djangofan Mar 20 '20 at 17:36