无法使用Mockito方法 [英] Mockito methods are not accessible

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

问题描述

我使用以下行号在我的项目上设置了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批注没有问题,但是我无法访问和使用诸如以下的模仿方法:

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.

一旦可以使用,请尝试使用David提到的静态导入:

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.同样,您也可以使用通配符,但是根据此SO答案

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添加到收藏夹(窗口">偏好设置">"Java">编辑器">内容辅助">收藏夹">新类型")中,以便所有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天全站免登陆