'中的代码如何失败?'阻止工作?我知道它是一个闭包,但无论我调用是否正在使用其签名,代码都会被调用。此外," ReadOnlyPropertyException"的处理是什么?出现在括号中?如果它是一个参数,那么它不会像官方文档中列出的那样设置!!
问题:什么是' shouldFail'?应该怎么调用?如何处理这个方法/函数/闭包据称抛出的异常?
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.
}
答案 0 :(得分:1)
shouldFail()
(在此变体中)接受一个类和一个闭包。它运行闭包并报告测试失败,如果闭包没有通过抛出该类型的异常而退出。至于捕获异常,你不会 - shouldFail()
为你做这件事。
(阅读评论及其周围的代码,看起来这个单元测试应传递,因为设置.ssn
的{{1}}属性会失败因为它是一个只读属性,导致GroovyPerson
。)