9

I have the following method outside the test method

private DynamicBuild getSkippedBuild() {
    DynamicBuild build = mock(DynamicBuild.class);
    when(build.isSkipped()).thenReturn(true);
    return build;
}

but when I call this method I get the following error

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at LINE BEING CALLED FROM

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!

Looks like mockito is not happy when you stub outside the test method. Is that not supported ?

EDIT: I can get this to work by doing the stubbing in @Test method but I want to reuse the stubbing across @Tests.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Surya
  • 4,922
  • 8
  • 41
  • 54

1 Answers1

15

If isSkipped() is not a final method, this problem probably indicates that you try to stub a method while stubbing of another method is in progress. It's not supported because Mockito relies on order of method invocations (when(), etc) in its stubbing API.

I guess you have something like this in your test method:

when(...).thenReturn(getSkippedBuild());

If so, you need to rewrite it as follows:

DynamicBuild build = getSkippedBuild();
when(...).thenReturn(build);
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • 4
    How is it unhelpful? It told you there was unfinished stubbing. It told you the line where the unfinished stubbing was. You also got a stack trace of where the error was actually triggered (that is, the stack from where you tried to stub the second method, while the stubbing of the first method was unfinished). What more would you have liked Mockito to tell you, when you have unfinished stubbing? – Dawood ibn Kareem Nov 05 '13 at 21:14
  • 4
    @DavidWallace I was looking for a missing thenReturn() like the error suggested. I would have liked mockito to tell me that inline mocking doesn't work. – Surya Nov 08 '13 at 23:12
  • Inline mocking DOES work, just not when you're in the middle of mocking something else; in other words, you can't do more mocking inside a call to `thenReturn` . A detailed explanation of this distinction could be added to the error message, I suppose, but it would have made the error message extremely long. If you like, I can talk to the rest of the Mockito team about adding a more detailed explanation to the Mockito documentation; but adding it to the error message just isn't the right place. – Dawood ibn Kareem Nov 09 '13 at 01:56