Search code examples
javaunit-testingmockingmockitopowermockito

Unfinished stubbing detected here


I have a class like below:

public class ClassOne {

    public void function1(InputStream input, OutputStream output, Context context) {
    .....
    function2(List, String, String);
    } 
    
    private void function2(List, String, String){...}
}

I am trying to write unit test for this class which looks like:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassOne.class)
public class ClassOneTest {
    private ClassOne classVar;
    private ClassOne classSpy;
    
    @Before
    public void setup() {
        classVar = new ClassOne();
        classSpy = new ClassOne(classVar);
    }
   
    @Test
    public void testFunction1() {
        ....
        PowerMokito.doNothing().when(classSpy, "function2", List, string, string);
    }

}

I get this error in my unit test at the above:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at org.powermock.core.classloader.ClassloaderWrapper.runWithClassClassLoader(ClassloaderWrapper.java:51)

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, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

I reviewed several posts but nothing helped me till now. Any help would be much appreciated!


Solution

  • You didn't call spy() and this cause the issue

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(ClassOne.class)
    public class ClassOneTest {
    
        private ClassOne classVar;
        private ClassOne classSpy;
        
        @Before
        public void setup() {
            classVar = new ClassOne();
            classSpy = spy(new ClassOne(classVar));
        }
    
        @Test
        public void testFunction1() {
            // Arrange
            PowerMokito.doNothing().when(classSpy, "function2", List, string, string);
    
            // Act
            ....
        }
    }