Wednesday, March 24, 2010

Eclipse and Mockito

Mockito is great. A big part of it is the syntactic sugar, which relies on using static imports. Eclipse, by default, removes static imports when you use 'Organize Imports' (Ctrl+Shift+O). This saddened me, so I found a way to fix it. Thanks go to this post on static import content assist and the post it links on organize imports. I will repeat both instructions in here in one place.

Part 1: Tell Eclipse Not To Remove My Precious Static Imports
  1. Open Preferences (Window-> Preferences)
  2. Browse to Java -> Code Style -> Organize Imports
  3. Change 'Number of static imports needed for .* to '1' 
  4. Click Ok 
Part 2: Get Eclipse to Create the Mockito Static Import for Me
  1. Open Preferences (Window -> Preferences)
  2. Browse to Java -> Editor -> Content Assist -> Favorites
  3. Click 'New Type...'
  4. Enter org.mockito.Mockito
  5. Click Ok twice. 
Now you can write unit tests with Mockito in Eclipse without issues. You can now type mock and ctrl+space and Eclipse will add the static import for you. It will also leave it alone when you Organize Imports going forward. No more trying to remember not to Ctrl+Shift+O when editing a mockito test.

No comments:

Post a Comment