简体   繁体   中英

Mock/Stub a RuntimeException in unit test

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)

@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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM