我尝试了Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock中提供的解决方案,而且这个问题也是Mockito - Wanted but not invoked: Actually, there were zero interactions with this mock但仍然遇到同样的错误。我错过了什么吗? 这是我的实施: -
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);
}
}
答案 0 :(得分:3)
您需要传入模拟类(或使用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();
}
}