0

我想测试我的应用程序并检查它是否正确处理 NullPointerExceptions。

我有两个想法如何做到这一点:

throw new NullPointerException();

和:

((Object) null).hashCode();

它们都产生相同的堆栈跟踪。

第二个对我来说“更真实”,因为这是在我的真实代码中会发生的事情。

这两种说法有区别吗?我应该使用哪个?

4

3 回答 3

2

Use directly

throw new NullPointerException();

Because,JRE throws NullPointerException when

  • Calling the instance method of a null object.

  • Accessing or modifying the field of a null object.

  • Taking the length of null as if it were an array.

  • Accessing or modifying the slots of null as if it were an array.

  • Throwing null as if it were a Throwable value.

When you do this

((Object) null).hashCode();

You met the first condition and JRE throws the NPE.

Finally You are increasing one more step. That's it. No Difference.

于 2013-10-15T13:30:10.707 回答
2

利用

throw new NullPointerException();

因为您想测试您的应用程序NullPointerException是否正确处理 a 。

于 2013-10-15T13:27:44.090 回答
0

如文档所述,这两行代码都会引发相同的异常。除非您想测试 JRE / Java(这完全没有必要),否则就测试策略而言,这两行之间没有区别。

于 2013-10-15T13:35:08.767 回答