Mockito无法存根重载的void方法

时间:2018-01-19 00:00:25

标签: java unit-testing mockito

我正在使用一些抛出异常的库,并希望在抛出异常时测试我的代码是否正常运行。对其中一个重载方法进行存根似乎不起作用。我收到此错误: Stubber无法应用于void。不存在变量类型T的实例类型,因此void确认为T

`public class AnotherThing {
  private final Something something;

  public AnotherThing(Something something) {
    this.something = something;
  }

  public void doSomething (String s) {
    something.send(s);
  }
}

public class Something {

  void send(String s) throws IOException{

  }

  void send(int i) throws IOException{

  }
}

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class OverloadedTest {

  @Test(expected = IllegalStateException.class)
  public void testDoSomething() throws Exception {
    final Something mock = mock(Something.class);
    final AnotherThing anotherThing = new AnotherThing(mock);

    doThrow(new IllegalStateException("failed")).when(anotherThing.doSomething(anyString()));
  }
}`

1 个答案:

答案 0 :(得分:4)

您错放了右括号。使用doVerb().when()语法时,对when的调用应包含该对象,这使得Mockito有机会停用存根期望并且还会阻止Java认为您正在尝试在任何地方传递void值。

doThrow(new IllegalStateException("failed"))
    .when(anotherThing.doSomething(anyString()));
//                    ^ BAD: Method call inside doVerb().when()

doThrow(new IllegalStateException("failed"))
    .when(anotherThing).doSomething(anyString());
//                    ^ GOOD: Method call after doVerb().when()

请注意,这与不使用when时的doVerb来电不同:

//               v GOOD: Method call inside when().thenVerb()
when(anotherThing.doSomethingElse(anyString()))
    .thenThrow(new IllegalStateException("failed"));