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 @Test
s.
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.
@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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With