Java 例外:需要mockito,但没有调用,实际上与此mock没有任何交互
我有接口Java 例外:需要mockito,但没有调用,实际上与此mock没有任何交互,java,unit-testing,mockito,Java,Unit Testing,Mockito,我有接口 Interface MyInterface { myMethodToBeVerified (String, String); } 并介绍了接口的实现 class MyClassToBeTested implements MyInterface { myMethodToBeVerified(String, String) { ……. } } 我还有一节课 class MyClass { MyInterface myObj = new MyClassTo
Interface MyInterface {
myMethodToBeVerified (String, String);
}
并介绍了接口的实现
class MyClassToBeTested implements MyInterface {
myMethodToBeVerified(String, String) {
…….
}
}
我还有一节课
class MyClass {
MyInterface myObj = new MyClassToBeTested();
public void abc(){
myObj.myMethodToBeVerified (new String(“a”), new String(“b”));
}
}
我正在尝试为我的类编写JUnit。我已经做了
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String(“a”), new String(“b”));
}
}
但是我得到了所需的mockito,但没有被调用,实际上在验证调用时没有与这个mock的交互
任何人都可以提出一些解决方案。您需要在正在测试的类中注入mock。此时,您正在与真实对象交互,而不是与模拟对象交互。您可以通过以下方式修复代码:
void testAbc(){
myClass.myObj = myInteface;
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
虽然在
@Before
void setUp(){
myClass = new myClass();
myClass.myObj = myInteface;
}
@Test
void testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
@Jk1的答案很好,但Mockito还允许使用注释进行更简洁的注入:
@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface
但无论使用哪种方法,注释都不会被处理(甚至@Mock),除非您以某种方式调用static
MockitoAnnotation.initMocks()
或使用@RunWith(MockitoJUnitRunner.class)注释类您的类MyClass
创建一个新的MyClassToBeTested
,而不是使用你的模拟。描述了两种处理此问题的方法。@jk1的答案非常完美,因为@igor Ganapolsky问我们为什么不能在这里使用Mockito.mock?我发布了这个答案
为此,我们为myobj提供了一个setter方法,并使用mocked对象设置myobj值
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
在我们的测试类中,我们必须编写以下代码
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
为什么我们不能在这里使用Mockito.mock?@IgorGanapolsky:我们可以使用Mockito.mock,因为我们必须为myObj使用一个setter方法,并将mock对象设置为myObj.HikariDataSourceProvider dataSourceProvider=mock(dataSourceProvider.class);验证(dataSourceProvider).shutdown();有什么问题吗