Skip to content

Instantly share code, notes, and snippets.

@andrezrv
Last active December 23, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrezrv/6690428 to your computer and use it in GitHub Desktop.
Save andrezrv/6690428 to your computer and use it in GitHub Desktop.
How to test exceptions in Grails using Spock.
package myapp.mypackage
/**
* Just an example of a domain class.
* @author andrezrv
*/
class MyObject {
String name
String value
/**
* Get a an object given its name.
*
* @param name
* @return MyObject
*/
static def obtain( name ) {
def myObject = MyObject.findByName( name )
if ( !myObject.equals( null ) ) {
return myObject
}
throw new Exception( 'Object not found' )
}
}
package myapp.mypackage
import grails.test.mixin.TestFor
import grails.test.mixin.Mock
import spock.lang.Specification
/**
* See the API for {@link grails.test.mixin.services.ServiceUnitTestMixin} for usage instructions
* @author andrezrv
*/
@TestFor( MyObject )
@Mock( [ MyObject ] )
class MyServiceSpec extends Specification {
void testObtain() {
def myObject = new MyObject( name: 'Foo', value: 'Bar' )
myObject.save()
def myIncompleteObject = new MyObject()
given: // Obtain object with a valid instance.
def result = MyObject.obtain( myObject.name )
expect:
myObject == return
when : // Obtain object with an incomplete unsaved instance.
result = MyObject.obtain( myIncompleteObject )
then:
Exception e = thrown()
'Object not found' == e.message
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment