[英]Mock/Stub a RuntimeException in unit test
In School
class, I have a start()
function which invokes another function doTask()
: 在School
类中,我有一个start()
函数,该函数调用另一个函数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
: 我想使用RuntimeException
start()
进行单元测试:
@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? 我的实现代码不容易抛出RuntimeException
,如何使测试代码模拟RuntimeException并抛出它?
(Besides pure JUnit, I am considering using Mockito , but not sure how to throw 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"));
}
You can use when
with thenThrow
to throw exception. 您可以将when
与thenThrow
一起使用以引发异常。
You can use PowerMockito to mock the private method to throw a RuntimeException
. 您可以使用PowerMockito模拟私有方法以抛出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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.