Search code examples
javaexceptionjunitjunit4

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


I've a JUnit which I want to use to test for exceptions. It's like this:

@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() is like this:

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

For what I want, my test is fine when just considering method1(). My problem is that method2() is called by method1() and can also throw an exception. It's like this:

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

It's possible that no exception is thrown by method1() but then gets thrown by method2(). I'd like my test to check for an exception from either but I'm not sure how to factor method2() into my test, especially as it's a private void method. Can this be done and if so, how?


Solution

  • According to your code it is possible only if you can achieve true condition in this if:

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

    If for some reasons you couldn't prepare such kind of condition in the unit tests (say, Internet connection is needed) you may extract the condition checking into new method:

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

    In the test class you override new method and return what you want:

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

    This is more compact way to test exceptional cases:

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    
    @Test
    public void testMethod1WhenMethod2ThrowsException() throws Exception {
        thrown.expect(Exception.class);
        thrown.expectMessage("expected exception message");
    
        myServive.method1();
    }