Groovy Tip 14 Assert
def
static
test
(String str1,String str2)
{
println
"str1 size: ${str1.length()},str2 size: ${str2.length()}"
}
test
(
null
,
'123'
)
结果就报如下的错误:
Exception in thread "main"
java.lang.NullPointerException
: Cannot invoke method length() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(
NullObject.java:77
)
……
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeStaticmethodN(
ScriptBytecodeAdapter.java:212
)
at base.Testor2.main(
Testor2.groovy:17
)
这个错误提示比较长,我省略了中间的一大部分。从这个错误提示可以看出这是一个空指针错误,并且是调用“
length()
”方法的对象为空。这个错误提示已经很详细了,也相当的明白。但是我们的“
test(
String str1,String str2
)
”方法中,有两个对象调用了“
length()
”方法,即“
str1
”和“
str2
”,对于这样的一个提示,我们仍然搞不清楚是“
str1
”为空,还是“
str2
”为空。
def
static
test
(String str1,String str2)
{
if
(str1==
null
)
{
}
else
if
(str2==
null
)
{
println
'The second argument can not be null'
}
else
{
println
"str1 size: ${str1.length()},str2 size: ${str2.length()}"
}
}
下面来进行测试:
test
(
null
,
'123'
)
结果为:
The first argument can not be null
通过上面的分析,我们知道上面的解决方法是也是不太好的。
def
static
test
(String str1,String str2)
{
if
(str1==
null
)
{
}
else
if
(str2==
null
)
{
throws
new
MyNullException(
'The second argument can not be null'
);
}
else
{
println
"str1 size: ${str1.length()},str2 size: ${str2.length()}"
}
}
而使用
Assert
则没有上述的各种烦恼,请看下面的例子:
def
static
test
(String str1,String str2)
{
assert
str2!=
null
,
'The second argument can not be null'
println
"str1 size: ${str1.length()},str2 size: ${str2.length()}"
}
测试代码如下:
test
(
null
,
'123'
)
测试结果为
:
Exception in thread "main" java.lang.AssertionError: The first argument can not be null. Expression: (str1 != null). Values: str1 = null
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.assertFailed(
ScriptBytecodeAdapter.java:676
))
……
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeStaticmethodN(
ScriptBytecodeAdapter.java:212
)
at base.Testor2.main(
Testor2.groovy:19
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。