简体   繁体   中英

Mockito unable to stub overloaded void methods

I am using some library that throws an exception and would like to test that my code behaves correctly when the exception is thrown. Stubbing one of the overloaded methods does not seem to work. I am getting this error: Stubber cannot be applied to void. No instance types of variable type T exists so that void confirms to 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()));
  }
}`

You've misplaced the close parenthesis. When using doVerb().when() syntax, the call to when should only contain the object, which gives Mockito a chance to deactivate stubbed expectations and also prevents Java from thinking you're trying to pass a void value anywhere.

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()

Note that this is different from when calls when not using doVerb :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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