Sunday, 13 January 2019

Groovy: Assertions


Assertions are used to check the preconditions.

Syntax
assert [left expression] == [right expression] : (optional message)

If assertion succeeds, the nothing will happen. But if assertion fails, then groovy provides information about each sub-expressions of the expression being asserted.

HelloWorld.groovy
assert true

int x = 1
assert x == 1

int y = 2
assert y == 1 : "y is not equal to 1"	//This assertion fails

When you can above application, you can see below messages in console.

Caught: java.lang.AssertionError: y is not equal to 1. Expression: (y == 1). Values: y = 2
java.lang.AssertionError: y is not equal to 1. Expression: (y == 1). Values: y = 2
        at HelloWorld.run(HelloWorld.groovy:7)

If you omit the custom error message, then groovy generates the default message to the console.


HelloWorld.groovy
int y = 2
assert y == 1 //This assertion fails


When you execute 'HelloWorld.groovy', you can see below error messages in console.

Caught: Assertion failed:

assert y == 1 //This assertion fails
       | |
       2 false

Assertion failed:

assert y == 1 //This assertion fails
       | |
       2 false

        at HelloWorld.run(HelloWorld.groovy:2)

In the below application, I used assertion statement to make sure that, input to the factorial function is >= 0.


HelloWorld.groovy

int factorial(int n){
	assert (n >= 0)
	
	int result = 1
	for(int i = 1; i <= n; i++){
		result *= i
	}
	
	return result
}

print "Factorial of 5 : " + factorial(5)



Previous                                                 Next                                                 Home

No comments:

Post a Comment