Last active
December 23, 2015 20:29
-
-
Save andrezrv/6690428 to your computer and use it in GitHub Desktop.
How to test exceptions in Grails using Spock.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' ) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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