5

Java: NPE和单测覆盖率

 3 years ago
source link: https://www.felix021.com/blog/read.php?2239=
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Java: NPE和单测覆盖率

Java: NPE和单测覆盖率 不指定

切到新语言就是不断地踩坑呀。

手头有一个函数,输入一个 itemList,统计不同类型的个数,核心代码如下:
int xCount = 0, yCount = 0;
switch(typeParser.parse(item)) {
  case X:
    xCount++;
    break;
  case Y:
    yCount++;
    break;
  default:
    log.error("unknown type");
    break;
}
其他 typeParser 在遇到异常数据时会返回 null。

重构的时候,稳妥起见为它写了个单测,结果就在上述代码的第二行 NPE 了。

debug 时确认了 typeParser 和 item 都不是 null,猜测是 switch 不能处理 null ,但不熟悉 java 语法,搜了一下,果然如此。

由于 case 数量不多,就暂且改成了 if ... else if ... else 的结构。

由此可见,单测对于代码的覆盖率确实是很有帮助。



欢迎扫码关注:

weixin1.png

转载请注明出自 https://www.felix021.com/blog/read.php?2239 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK