Search code examples
unit-testingmockitojmockit

Wanted but not invoked. Actually, there were zero interactions with this mock


I tried solution given in Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock and this one too Mockito - Wanted but not invoked: Actually, there were zero interactions with this mock but Still getting the same error. Am I missing something? Here is me implementation:-

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;

class ClassOne {
    public void method(ClassTwo two) {
    }
}

class ClassTwo {
    public ClassTwo(String value) {
    }
}

class MyClassTwo extends ClassTwo {
    public MyClassTwo(String value) {
        super(value);
    }
}

class ClassToBeTested {
    ClassOne classOne;

    public ClassToBeTested() {
        classOne = new ClassOne();
    }

    public void methodToBeTested() {
        ClassTwo event = new MyClassTwo("String");
        classOne.method(event);
    }
}

@RunWith(MockitoJUnitRunner.class)
public class ClassToBeTestedTest {

    ClassToBeTested presenter;
    @Mock
    ClassOne classOne;

    @Before
    public void setUp() {
        presenter = new ClassToBeTested();
    }


    @Test
    public void testAbc() {
        presenter.methodToBeTested();
        ClassTwo event = new MyClassTwo("someString");
        verify(classOne).method(event);
    }
}

Solution

  • You need to pass in the mocked class (or do something horrid with PowerMock).

    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.runners.MockitoJUnitRunner;
    
    import static org.mockito.Mockito.verify;
    
    class ClassWeWantToBeMocked {
        void methodToBeMocked() { }
    }
    
    class ClassToBeTested {
        ClassWeWantToBeMocked dependency;
    
        // Notice that the dependency is now passed in. 
        // This is commonly called Dependency Injection.
        public ClassToBeTested(ClassWeWantToBeMocked dependency){
            this.dependency = dependency;
        }
    
        public void methodToBeTested(){
            dependency.methodToBeMocked();
        }
    }
    
    @RunWith(MockitoJUnitRunner.class)
    public class ClassToBeTestedTest {
    
        ClassToBeTested presenter;
    
        @Mock
        ClassWeWantToBeMocked ourMock;
    
        @Before
        public void setUp(){
            // Notice how we now pass in the dependency (or in this case a mock)
            presenter=new ClassToBeTested(ourMock);
        }
    
        @Test
        public void myMockTest(){
            presenter.methodToBeTested();
    
            verify(ourMock).methodToBeMocked();
        }
    }