2

In School class, I have a start() function which invokes another function doTask():

pubic class School {
    public void start() {
       try {
         doTask();
       } catch(RuntimeException e) {
          handleException();
       }
    }
    private void doTask() {
      //Code which might throw RuntimeException
    }
}

I want to unit test start() with RuntimeException:

@Test
public void testStartWithException() {
  // How can I mock/stub mySchool.start() to throw RuntimeException?
  mySchool.start();
}

It is not easy for my implementation code to throw the RuntimeException, how can I make the test code to mock a RuntimeException & throw it?

(Besides pure JUnit, I am considering using Mockito, but not sure how to throw RuntimeException)

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • Possible duplicate of [Mockito test a void method throws an exception](http://stackoverflow.com/questions/15156857/mockito-test-a-void-method-throws-an-exception) – randers Dec 31 '15 at 09:43
  • 1
    Why does doTask() throw an exception? If it's because of bad inputs, just use bad inputs in the test. If it's because of an interaction with a service that has an unexpected issue, you need to mock or stub out that service to make it throw an exception to simulate the issue. – aro_tech Dec 31 '15 at 11:35

2 Answers2

6
@Test
public void testStartWithException() {
  // How can I mock/stub mySchool.start() to throw RuntimeException?
  when(mySchool.start()).thenThrow(new RuntimeException("runtime exception"));
}

You can use when with thenThrow to throw exception.

chengpohi
  • 14,064
  • 1
  • 24
  • 42
1

You can use PowerMockito to mock the private method to throw a RuntimeException. Something like this:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.powermock.api.mockito.PowerMockito.doThrow;
import static org.powermock.api.mockito.PowerMockito.spy;

@RunWith(PowerMockRunner.class)
@PrepareForTest(School.class)
public class SchoolTest {

    @Test
    public void testStartWithException() throws Exception {
        School school = spy(new School());

        doThrow(new RuntimeException()).when(school, "doTask");    

        school.start();
    }
}
wjans
  • 10,009
  • 5
  • 32
  • 43
  • This looks more like the answer that Leem.fin is looking for, but whenever you have to use Powermockito instead of Mockito, it may be a sign that the design could be improved. – aro_tech Dec 31 '15 at 11:38