【问题标题】:NullPointerException in JUnitJUnit 中的 NullPointerException
【发布时间】:2017-06-16 16:48:05
【问题描述】:

我正在运行这个 JUint 测试方法,并且在运行时遇到异常 NullPointerException。这个异常怎么处理?

@Test
public void testDivision1() {
    System.out.println("testDivision");`
    Operation instance = new Operation(100, 2, null);
    int res = instance.calculate();
    assertEquals(50, res);

}

【问题讨论】:

  • Operation 长什么样子?
  • 公共类操作 { private final int firstOperand; private final int secondOperand;私有最终 EnumOp 运算符;公共操作(int firstOperand,int secondOperand,EnumOp 运算符){ this.firstOperand = firstOperand; this.secondOperand = secondOperand; this.operator = 运算符; } public int calculate() { return operator.calculate(firstOperand, secondOperand); } }
  • 请使用该代码更新您的问题。

标签: exception-handling nullpointerexception


【解决方案1】:

当你在这里通过null 换成EnumOp operator

Operation instance = new Operation(100, 2, null);

我假设这个操作失败了

return operator.calculate(firstOperand, secondOperand);

您应该为测试设置一个有效的EnumOp

【讨论】:

  • @Test public void testDivision1() throws NullPointerException { try { System.out.println("testDivision");操作实例 = new Operation(100, 2, null); int res = instance.calculate(); assertEquals(50, res); } catch (NullPointerException e) { System.out.println("error"); } }
  • 可以同时添加 throws 和 try,catch 吗?
  • 有可能,但在这里没有意义。你说'这个方法会抛出 NPE,但无论如何我都会抓住它'。想一想,你想测试什么?测试分区是否正常工作?或者如果抛出异常?
  • 是的,如果我不使用 throws 也没问题。实际上,我没有让 wen 添加 throws 以及何时添加 try,catch。
  • 看看这个:stackoverflow.com/questions/3241571/… 我的回答有用吗?然后接受它并暂时关闭问题。
猜你喜欢
  • 2013-10-28
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 2014-11-12
相关资源
最近更新 更多