Mockito 方法不可访问 [英] Mockito methods are not accessible

查看:23
本文介绍了Mockito 方法不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用以下 maven 行设置了 mockito:

I have mockito setup on my project with this maven lines:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.8.5</version>
    <scope>test</scope>
</dependency>

使用 @Mock 注释没有问题,但我无法访问和使用 mockito 方法,例如:

I have no problems to use the @Mock annotation but I can't access and use mockito methods like:

when(someMock.someMethod()).thenReturn();

Eclipse 只是无法识别它们.

Eclipse just does not recognize them.

请帮忙.

推荐答案

尝试调用 Mockito.when(foo.getBar()).thenReturn(baz)Mockito.verify(foo).getBar(),不依赖静态导入.@Mock 注解在技术上是一个类,而 whenverify 是 Mockito 类的静态方法.

Try calling Mockito.when(foo.getBar()).thenReturn(baz) and Mockito.verify(foo).getBar(), which won't rely on static imports. Unlike the @Mock annotation, which is technically a class, when and verify are static methods on the Mockito class.

一旦你有这个工作,然后尝试大卫提到的静态导入:

Once you have that working, then try the static imports to which David alluded:

import static org.mockito.Mockito.when;   // ...or...
import static org.mockito.Mockito.*;      // ...with the caveat noted below.

这将允许您在不指定 Mockito 类的情况下使用 Mockito.when.您也可以使用通配符,但是根据 this SO answer Java 文档 建议谨慎使用通配符——尤其是因为它可能会在类似情况下中断——命名的静态方法稍后会添加到 Mockito.

This will then allow you to use Mockito.when without specifying the Mockito class. You can also use a wildcard, as so, but per this SO answer the Java docs recommend using wildcards sparingly--especially since it can break if a similarly-named static method is ever added to Mockito later.

添加 import org.mockito.*; 是不够的,因为这会添加 org.mockito 包中的所有类,而不是 org.mockito 上的方法.Mockito.

Adding import org.mockito.*; is insufficient because that adds all classes in the org.mockito package, but not the methods on org.mockito.Mockito.

特别是对于 Eclipse,您可以通过将光标放在 Mockito.whenwhen 部分并按 Control-Shift-M(添加进口").您还可以将 org.mockito.Mockito 添加到您的收藏夹(Window > Preferences > Java > Editor > Content Assist > Favorites > New Type),以便所有 Mockito 静态方法都显示在您的 Ctrl-Space 内容中即使您没有专门导入它们,也会提示提示.(您可能还想对 org.mockito.Matchers 执行此操作,技术上可通过继承在 org.mockito.Mockito 上使用它们,但由于这个原因可能不会出现在 Eclipse 中.)

For Eclipse in particular, you can add a static import by putting the cursor on the when part of Mockito.when and pressing Control-Shift-M ("Add import"). You can also add org.mockito.Mockito to your Favorites (Window > Preferences > Java > Editor > Content Assist > Favorites > New Type) so that all Mockito static methods show up in your Ctrl-Space content assist prompt even if you haven't imported them specifically. (You may also want to do this for org.mockito.Matchers, which are technically available on org.mockito.Mockito via inheritance, but may not show up in Eclipse for that reason.)

这篇关于Mockito 方法不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆