我有接口
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”));
}
}
我正在尝试为 MyClass 编写 JUnit。我已经做到了
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String(“a”), new String(“b”));
}
}
但是我需要 mockito 但没有被调用,实际上在验证调用时与此模拟的交互为零。
任何人都可以提出一些解决方案吗?
void testAbc(){
myClass.myObj = myInteface;
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
尽管将所有初始化代码提取到
@Before
@Before
void setUp(){
myClass = new myClass();
myClass.myObj = myInteface;
}
@Test
void testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface
但是无论您使用哪种方法,注释都不会被处理(甚至您的 @Mock 也不会被处理),除非您以某种方式调用静态
MockitoAnnotation.initMocks()
或使用
@RunWith(MockitoJUnitRunner.class)
注释类。
为此,我们为 myobj 提供了一种 setter 方法,并使用模拟对象设置 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"));
}
}
例如,如果你有一些单元测试说验证 thisMethod() 被执行,但实际上,这并不是因为 varX 和 varY 不相等。
//method expected to be called.
if( varX == varY){
thisMethod();
}
//test
Mockito.verify(foo).thisMethod();
@模拟 类名 类名; …… verify(className).method(argument1, argument2); //实际代码
在这种情况下,没有为 junit 调用 className.class。 将其设为 =>的代码
@模拟 类类名; …… 类名 类名 = mock(类名.class); //调用junit的className。 verify(className).method(argument1, argument2);