-2

When I run the following code I get exception, and this is OK because string [0] is “1” and not 2

So assert make this exception and break from code ….

But what I want to do:

is to print NOT equal in case assert string[0] isn’t 1 , and ignore the exception

Else

in case string[0] is 1

then the code will print equal

  string = "1 2 3"

  assert string[0]          == '2'

  println "continue"

.

Exception thrown

Assertion failed: 

assert string[0]          == '2'
              |     |            |
              1 2 3 1            false
tim_yates
  • 167,322
  • 27
  • 342
  • 338
maihabunash
  • 1,632
  • 9
  • 34
  • 60

1 Answers1

2

The point of having as assertion is deviated if you desire to eat the exception on failed Assertion. What you are looking for can be achieved easily by an if/else block as mentioned in the question header.

Just for the sake of verbosity you can add a message to the assertion in either of the below ways, but you would still get an exception on failure:

assert string[0] == '2' : 'Not Equal'

// or 
assert string[0] == '2', 'Not Equal'

should give a message as

java.lang.AssertionError: Not Equal. Expression: (string[0] == 2). 
Values: string = 1 2 3
dmahapatro
  • 49,365
  • 7
  • 88
  • 117