当前位置: 首页 > 知识库问答 >
问题:

想要但没有调用。实际上,与这个模拟没有任何交互

梁和颂
2023-03-14

我尝试了例外情况下给出的解决方案:mockito想要但没有调用,实际上与这个mock没有任何交互,而这个mockito也想要但没有调用:实际上,与这个mock没有任何交互但仍然得到相同的错误。我是不是漏掉了什么?以下是me的实现:-

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

共有1个答案

孔飞舟
2023-03-14

您需要传入mocked类(或者使用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();
    }
}
 类似资料: