想要但没有调用。实际上,与此模拟的交互为零

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

我尝试了 Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock and this one too 中给出的解决方案,但仍然出现相同的错误。我错过了什么吗? 这是我的实现:-

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);
    }
}

你需要传入模拟的 class(或者用 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();
    }
}