在单元测试中模拟/存根RuntimeException

时间:2015-12-31 09:40:33

标签: java unit-testing junit mockito

School课程中,我有一个start()函数调用另一个函数doTask()

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

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

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

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

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

2 个答案:

答案 0 :(得分:3)

var client = new ElasticClient(new ConnectionSettings(new Uri("http://localhost:9200")));

var response = client.Map<object>(d => d
    .Index("songs")
    .Type("song")
    .Properties(props => props
        .String(s => s
            .Name("name"))
        .Completion(c => c
            .Name("suggest")
            .IndexAnalyzer("simple")
            .SearchAnalyzer("simple")
            .Payloads())));

Debug.Assert(response.IsValid);

您可以@Test public void testStartWithException() { // How can I mock/stub mySchool.start() to throw RuntimeException? when(mySchool.start()).thenThrow(new RuntimeException("runtime exception")); } 使用when来抛出异常。

答案 1 :(得分:1)

您可以使用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();
    }
}