Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()));
  }
}`
like image 744
nokostar Avatar asked Jan 28 '23 20:01

nokostar


1 Answers

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"));
like image 156
Jeff Bowman Avatar answered Feb 06 '23 10:02

Jeff Bowman