groovy中应该失败的是什么?
“shouldFail”块中的代码是如何工作的?我知道这是一个闭包,但是不管我调用的代码是否使用它的签名,代码都会被调用。此外,括号中出现的“ReadOnlyPropertyException”是怎么回事?如果它是一个参数,那么它不是按照官方文档中列出的设置 问题:什么是“应该失败”?应该如何调用它?如何处理据称由该方法/函数/闭包引发的异常groovy中应该失败的是什么?,groovy,closures,Groovy,Closures,“shouldFail”块中的代码是如何工作的?我知道这是一个闭包,但是不管我调用的代码是否使用它的签名,代码都会被调用。此外,括号中出现的“ReadOnlyPropertyException”是怎么回事?如果它是一个参数,那么它不是按照官方文档中列出的设置 问题:什么是“应该失败”?应该如何调用它?如何处理据称由该方法/函数/闭包引发的异常 void test02_ReadOnlyFieldInGroovyBean() { // You've probably noticed how
void test02_ReadOnlyFieldInGroovyBean() {
// You've probably noticed how Groovy automatically generates getters/setters for you. But what if you don't
// want to generate a setter because it's a read-only field? Just mark it with 'final'. Groovy will understand.
// Try to modify Ken's ssn. You should get a ReadOnlyPropertyException.
def person = new GroovyPerson('Ken', 'Kousen', '7878')
def failed = false
shouldFail (ReadOnlyPropertyException) {
// ------------ START EDITING HERE ----------------------
System.out.println(" i am in should fail")
person.ssn='8332';
// ------------ STOP EDITING HERE ----------------------
failed = false
System.out.println(" exiting should fail")
}
//def foobar=shouldFail("hjh");
//def foobar=true;
failed=shouldFail('abc');
//System.out.println("Failed: "+failed);
assert failed
// The code wrapping your additions verifies that the ReadOnlyProperty exception has been thrown.
// The curly brackets ({}) represent a closure. We'll get into what that means very soon.
}
shouldFail()
(在此变体中)接受一个类和一个闭包。如果闭包没有通过抛出该类型的异常退出,它将运行闭包并报告测试失败。至于捕获异常,您不需要-shouldFail()
为您这样做
见:
(阅读注释及其周围的代码,看起来此单元测试应该通过,因为设置
GroovyPerson
的.ssn
属性将失败,因为它是只读属性,导致ReadOnlyPropertyException
)非常有趣。。所以这是一个库函数!!啊!对Groovy.test
(构建于JUnit之上)中提供的Groovy增强的单元测试工具的一部分。但是我仍然不能确定我是否完全获得了它。该方法接受a)类,b)闭包。那么,它是否应该按如下方式调用:shouldFail(ReadOnlyPropertyException,{/*引发此异常的代码})??但它的调用如下:shouldFail(ReadOn…{/*失败的代码*/}((或者至少我认为它是这样被调用的))daggun it。。。这样做也很好:即shouldFail(ReadOnlyPropertyException,{/*抛出此异常的代码}),我相信两者都可以。但是,当方法的最后一个参数是闭包时,您可以将其放在右括号之后,以及参数的“正常”位置(之前)。