Mockito 无法存根重载的无效方法

nok*_*tar 4 java unit-testing mockito

我正在使用一些引发异常的库,并想测试我的代码在引发异常时的行为是否正确。存根重载方法之一似乎不起作用。我收到此错误:Stubber 不能应用于无效。不存在变量类型 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()));
  }
}`
Run Code Online (Sandbox Code Playgroud)

Jef*_*ica 8

你放错了右括号。使用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()
Run Code Online (Sandbox Code Playgroud)

请注意,这与when不使用时的调用不同doVerb

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