Prabu
Prabu

Reputation: 3728

Groovy assert continue on failure

I am using groovy scripts in my unit test. I have the following code snippet, and I'm using multiple asserts in my single test script.

def a ='welcome'
def b ='test'
def c ='welcome'

assert a==b
assert a==c

The first assertion was failed and execution was stopped. But I want to continue the further snippet of code.

similar to soft assert in selenium how should I collect all the failure exception in groovy.

Upvotes: 1

Views: 3054

Answers (2)

cfrick
cfrick

Reputation: 37033

If you want to abuse the assert for the "diff/debug-infos", you can catch the AssertionError. E.g.:

def a = 42
def b = 666

try {
    assert a==b
}
catch (AssertionError e) {
    println e.message
}
print "the end"

// assert a==b
//        || |
//        || 666
//        |false
//        42
// the end

Upvotes: 1

tune5ths
tune5ths

Reputation: 723

In Groovy and Java, AssertionErrors are errors which the program can't recover from. I would recommend setting up your unit tests to test/assert one thing per test. This is a best practice for unit tests and it makes it much easier to identify the cause of a test failure.

Your example makes it obvious which assertion has failed. Consider that as your build up tests, this will not necessarily be the case. With a single assertion per test you can identify the cause by the test name. If you were to validate using some other means than assert, having your test continue upon failure - it will be much less obvious which condition failed without analyzing the log.

Upvotes: 2

Related Questions