Finding import static statements for Mockito constructs

Russ Bateman picture Russ Bateman · Sep 6, 2011 · Viewed 104.2k times · Source

I'm trying to crash through the brick wall between me and Mockito. I've torn my hair out over trying to get correct import static statements for Mockito stuff. You'd think someone would just throw up a table saying that anyInt() comes from org.mockito.Matchers and when() comes from org.mockito.Mockito, etc., but that would be too helpful to newcomers, no?

This sort of thing, especially when mixed in with myriad more import statements ending in asterisks, isn't always very helpful:

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

Yes, I know about and have been trying to use the Eclipse Window -> Preferences-> Java -> Editor-> Content Assist -> Favorites mechanism. It helps, but it doesn't hit the nail on the head.

Any answers to this question would be appreciated.

Many thanks, Russ

Answer

Tony R picture Tony R · Sep 13, 2011

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.