Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito stubbing outside of the test method

Tags:

java

mockito

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.

like image 952
Surya Avatar asked Nov 05 '13 20:11

Surya


People also ask

What is Mockito stubbing?

Mocks and stubs are fake Java classes that replace these external dependencies. These fake classes are then instructed before the test starts to behave as you expect. More specifically: A stub is a fake class that comes with preprogrammed return values.

What is the difference between @mock and @InjectMocks?

@Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class. Annotated class to be tested dependencies with @Mock annotation.

How do you mock a method call inside another method in the same class?

We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.

What is Mockito lenient ()?

lenient() to enable the lenient stubbing on the add method of our mock list. Lenient stubs bypass “strict stubbing” validation rules. For example, when stubbing is declared as lenient, it won't be checked for potential stubbing problems, such as the unnecessary stubbing described earlier.


1 Answers

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);
like image 176
axtavt Avatar answered Sep 30 '22 17:09

axtavt