正在测试的方法调用 private void 方法,我也想将其包含在我的测试中

Method under test calling private void method which I'd also like to include in my test

我有一个 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 方法。可以这样做吗?如果可以,怎么做?

根据您的代码,只有您可以在此 if:

中实现 true 条件才有可能
  if (condition is not met) {
    do something...
    throw new Exception();
  } else {
    do something else;
  }

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

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

在测试中 class 你覆盖了新方法和 return 你想要的:

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();
}