查找 Mockito 构造的导入静态语句

我正试图穿过我和 Mockito 之间的砖墙。为了弄到正确的 导入静电干扰对莫基托作品的陈述,我已经抓狂了。你可能认为有人会抛出一张表,说 任何 Int ()来自 啊,仿真的,火柴什么时候来自 Org Mocito Mockito,等等,但这对新手来说太有帮助了,不是吗?

这类事情,尤其是当与无数以星号结尾的导入语句混在一起时,并不总是很有帮助:

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

是的,我知道并且一直在尝试使用 Eclipse Window-> Preferences-> Java-> Editor-> Content Assist-> Favorites机制。是有帮助,但不是一针见血。

如果你能回答这个问题,我将不胜感激。

非常感谢, 拉斯

133344 次浏览

The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.

One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.

Also, when using mocks, I try to avoid assertThat in favor other other assertions and verify, e.g.

assertEquals(1, 1);
verify(someMock).someMethod(eq(1));

instead of

assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));

If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

For is()

import static org.hamcrest.CoreMatchers.*;

For assertThat()

import static org.junit.Assert.*;

For when() and verify()

import static org.mockito.Mockito.*;

My imports

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;


import org.junit.Test;

And it works

import static org.mockito.Matchers.anyInt;

e.g. when(listMock.get(anyInt())).thenReturn("stackoverflow");