繁体   English   中英

Mockito无法存根重载的void方法

[英]Mockito unable to stub overloaded void methods

我正在使用一些抛出异常的库,并希望在抛出异常时测试我的代码是否正常运行。 对其中一个重载方法进行存根似乎不起作用。 我收到此错误: 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()));
  }
}`

你错放了右括号。 当使用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()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM