我有一堂课,我正在向我的服务中注入一个代理.
I have a class and I am injecting a proxy into my service.
Service service
{
private ServiceProxy proxy;
public Service(ServiceProxy proxy)
{
this.proxy = proxy;
}
}
对它的测试是:
ServiceTest
{
@Mock
ServiceProxy mockProxy;
Service service = new Service(mockProxy);
}
如果我像这样初始化我的类,当我想使用服务对象时,我总是会得到一个 NPE
.为什么 Mockito
会这样做?有什么简单的方法可以解决这个问题,而不是在每个测试中都声明它?
If I initialize my class like this I always get a NPE
when I want to use the service object. Why does Mockito
do this? What is an easy way around this instead of declaring it in each and every test?
如果你使用的是 Mockito 1.9.0 或更高版本,实现你想要的最好的方法是这样的:
Provided you are using Mockito version 1.9.0 or later, the best way to achieve what you want is like this:
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
private ServiceProxy proxy;
@InjectMocks
private Service service;
@Test
public void test() {
assertNotNull(service);
assertNotNull(proxy);
}
}
首先是 @RunWith(MockitoJUnitRunner.class)
声明,它将导致 @Mock 和 @InjectMocks 注释自动工作而无需任何显式初始化.第二件事是,从 Mockito 1.9.0 开始,@InjectMocks 注释可以使用 Constructor injection 机制,这是您的 Service 类的最佳选择.
First thing is the @RunWith(MockitoJUnitRunner.class)
declaration which will cause @Mock and @InjectMocks annotation to work automatically without any explicit initialization. The second thing is that starting with Mockito 1.9.0 @InjectMocks annotation can use the Constructor injection mechanism which is the best option for your Service class.
@InjectMocks 的其他选项是 Setter 注入 和 Field 注入(请参阅 docs 顺便说一句),但您需要一个无参数构造函数才能使用它们.
Other options for @InjectMocks are Setter injection and Field injection (see docs BTW) but you'd need a no argument constructor to use them.
总结一下 - 您的代码无法运行,因为:
So summarizing - your code cannot work because:
如果出于某种原因您不想使用@InjectMocks,唯一的方法是在测试方法主体或@Before 注释的setUp 方法中构造您的Service 对象.
If for some reason you don't want to use @InjectMocks, the only way is to construct your Service object within the test method body or within the @Before annotated setUp method.
这篇关于使用 Mockito 将模拟对象注入在测试中声明为字段的待测试对象不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!