|
17 | 17 | package grails.test.mixin.integration |
18 | 18 |
|
19 | 19 | import groovy.transform.CompileStatic |
| 20 | +import junit.framework.AssertionFailedError |
| 21 | +import org.codehaus.groovy.runtime.ScriptBytecodeAdapter |
20 | 22 | import org.junit.Before |
21 | 23 | import org.codehaus.groovy.grails.test.support.GrailsTestInterceptor |
22 | 24 | import grails.test.mixin.TestMixinTargetAware |
23 | | -import grails.util.Holders |
24 | 25 | import org.codehaus.groovy.grails.test.support.GrailsTestMode |
25 | 26 | import org.junit.After |
26 | 27 | import groovy.transform.TypeCheckingMode |
@@ -61,4 +62,60 @@ class IntegrationTestMixin implements TestMixinTargetAware { |
61 | 62 | void destoryIntegrationTest() { |
62 | 63 | interceptor?.destroy() |
63 | 64 | } |
| 65 | + |
| 66 | + /** |
| 67 | + * Asserts that the given code closure fails when it is evaluated |
| 68 | + * |
| 69 | + * @param code |
| 70 | + * @return the message of the thrown Throwable |
| 71 | + */ |
| 72 | + String shouldFail(Closure code) { |
| 73 | + boolean failed = false |
| 74 | + String result = null |
| 75 | + try { |
| 76 | + code.call() |
| 77 | + } |
| 78 | + catch (GroovyRuntimeException gre) { |
| 79 | + failed = true |
| 80 | + result = ScriptBytecodeAdapter.unwrap(gre).getMessage() |
| 81 | + } |
| 82 | + catch (Throwable e) { |
| 83 | + failed = true |
| 84 | + result = e.getMessage() |
| 85 | + } |
| 86 | + if (!failed) { |
| 87 | + throw new AssertionFailedError("Closure " + code + " should have failed") |
| 88 | + } |
| 89 | + |
| 90 | + return result |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Asserts that the given code closure fails when it is evaluated |
| 95 | + * and that a particular exception is thrown. |
| 96 | + * |
| 97 | + * @param clazz the class of the expected exception |
| 98 | + * @param code the closure that should fail |
| 99 | + * @return the message of the expected Throwable |
| 100 | + */ |
| 101 | + String shouldFail(Class clazz, Closure code) { |
| 102 | + Throwable th = null |
| 103 | + try { |
| 104 | + code.call() |
| 105 | + } catch (GroovyRuntimeException gre) { |
| 106 | + th = ScriptBytecodeAdapter.unwrap(gre) |
| 107 | + } catch (Throwable e) { |
| 108 | + th = e |
| 109 | + } |
| 110 | + |
| 111 | + if (th == null) { |
| 112 | + throw new AssertionFailedError("Closure $code should have failed with an exception of type $clazz.name") |
| 113 | + } |
| 114 | + |
| 115 | + if (!clazz.isInstance(th)) { |
| 116 | + throw new AssertionFailedError("Closure $code should have failed with an exception of type $clazz.name, instead got Exception $th") |
| 117 | + } |
| 118 | + |
| 119 | + return th.message |
| 120 | + } |
64 | 121 | } |
0 commit comments