Luc*_*cas 5 unit-testing mockito
我正在使用mockito来嘲笑我的服务..
如何在父类中注入模拟?
样本:
public abstract class Parent(){
@Mock
Message message;
}
public class MyTest() extends Parent{
@InjectMocks
MyService myService //MyService has an instance of Message
//When I put @Mock Message here it works
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,消息会Parent保留null
有两种方法可以解决这个问题:
1)您需要在父类的方法MockitoAnnotations.initMocks(this)中使用。@Before
以下对我有用:
public abstract class Parent {
@Mock
Message message;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
}
public class MyTest extends Parent {
@InjectMocks
MyService myService = new MyService(); //MyService has an instance of Message
...
}
Run Code Online (Sandbox Code Playgroud)
2)如果想使用@RunWith(MockitoJUnitRunner.class)上面的类定义,那么必须在Parent类中完成:
@RunWith(MockitoJUnitRunner.class)
public class Parent {
...
Run Code Online (Sandbox Code Playgroud)
@Mock请注意,在 theParent和class 中声明MyTest将导致注入的对象为 null。因此,您必须选择要在哪里声明这一点。