Mock/Stub单元测试中的RuntimeException



School类中,我有一个start()函数,它调用另一个函数doTask():

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

我想用RuntimeException:对start()进行单元测试

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

我的实现代码抛出RuntimeException并不容易,我如何使测试代码模拟RuntimeException&扔?

(除了纯JUnit,我正在考虑使用Mockito,但不确定如何抛出RuntimeException)

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

您可以将whenthenThrow一起使用来引发异常。

您可以使用PowerMockito来模拟抛出RuntimeException的私有方法。类似这样的东西:

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

相关内容

  • 没有找到相关文章

最新更新