【问题标题】:Mockito unable to stub overloaded void methodsMockito 无法存根重载的 void 方法
【发布时间】:2018-01-19 08:27:27
【问题描述】:

我正在使用一些引发异常的库,并且想测试我的代码在引发异常时是否正确运行。存根重载方法之一似乎不起作用。我收到此错误: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()));
  }
}`

【问题讨论】:

    标签: java unit-testing mockito


    【解决方案1】:

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

    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"));
    

    【讨论】:

    • 太棒了!这很有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2015-11-23
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    相关资源
    最近更新 更多