【问题标题】:Method under test calling private void method which I'd also like to include in my test被测方法调用私有 void 方法,我也想将其包含在我的测试中
【发布时间】:2023-03-15 01:36:01
【问题描述】:

我有一个 JUnit,我想用它来测试异常。是这样的:

@Test
public void test1() throws Exception {
  boolean testPass;
  try {
    method1();
    testPass = true;
    Assert.assertTrue(testPass);
  }
  catch(Exception e) {
    testPass = false;
    Assert.assertTrue(testPass);
  }
  System.out.println("End of test2 Junit");
}

method1()是这样的:

public void method1() throws Exception {
  try {
    do something....
    method2();
  } catch (Exception e) {
    throw e;
  } finally {
   do some more...
  }
}

对于我想要的,只要考虑method1().,我的测试就很好我的问题是method2()method1() 调用并且也可以抛出异常。是这样的:

private  void method2() throws Exception {
  if (confition is not met) {
    do something...
    throw new Exception();
  } else {
    do something else;
  }
}

有可能method1() 没有抛出异常,但随后method2() 又抛出了异常。我希望我的测试检查其中一个异常,但我不确定如何将 method2() 纳入我的测试,特别是因为它是 private void 方法。可以这样做吗?如果可以,怎么做?

【问题讨论】:

  • factor method2() into my test 是什么意思?是否要测试 method2()method1() 的逻辑?
  • 如果可能的话,我想要的只是在method1()method2() 中都没有抛出异常时通过 assertTrue 并且如果method1() 中抛出异常则失败或method2().
  • 在这种情况下,如果 method2() 抛出 Exception 或其任何子类,您的测试将失败。
  • 您应该测试 public 接口,而不是私有实现。单元测试应该是黑盒测试,因为测试关注从用户角度发生的事情。既然用户不能调用method2(),应该没有理由去测试它。测试的存在是为了确保实现给出例外的结果。如果method2() 抛出method1() 吞下的异常,那么用户首先不应该知道该异常。你为什么要测试它?您是否将method2() 的详细信息泄露到method1() 的合同中?如果是这样,那就是问题所在。
  • 啊,好的。谢谢你。

标签: java exception junit junit4


【解决方案1】:

根据您的代码,只有在此if 中达到真实条件才有可能:

  if (condition is not met) {
    do something...
    throw new Exception();
  } else {
    do something else;
  }

如果由于某些原因您无法在单元测试中准备此类条件(例如,需要 Internet 连接),您可以将条件检查提取到新方法中:

  if (isNotCondition()) {
    do something...
    throw new Exception();

在测试类中你重写新方法并返回你想要的:

MyService myService = new MyService() {
    @Override
    boolean isNotCondition() {
        return true;
    }
}

这是测试异常情况的更紧凑的方法:

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void testMethod1WhenMethod2ThrowsException() throws Exception {
    thrown.expect(Exception.class);
    thrown.expectMessage("expected exception message");

    myServive.method1();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2016-10-24
    • 2012-02-18
    相关资源
    最近更新 更多