在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"));
}
您可以将when
与thenThrow
一起使用来引发异常。
您可以使用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();
}
}