Eclipse Tip: Keep static imports for JUnit 4

If you are using Eclipse to write your JUnit 4 tests you might have noticed that when you organize the imports, the line

import static org.junit.Assert.*;

at the top of your JUnit 4 classes is replaced by stuff like:

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;

While your code still compiles and runs OK, this forces you to add another specific static import every time you want to use another static assert method like assertEquals.

Luckily this can be fixed by going to Windows/Preferences..., going to the Java/Code Style/Organize Imports tab and then entering 1 where it says "Number of static imports needed for .*" and then clicking the OK button.

Hope this helps!

Comments (9)

  1. p3t0r - Reply

    October 12, 2008 at 7:40 pm

    Also, add 'org.junit.Assert' or any of your static helper methods to your 'favorites' (preferences, search for favorites). This makes working with static imports much easier.

  2. Martin Tilma - Reply

    October 13, 2008 at 9:05 am

    I just wrote on the same issue ( but the solution differences a bit.

  3. p3t0r - Reply

    October 13, 2008 at 9:13 pm

    @Martin Tilma ... that is exactly what I said in my first comment... but thanks for elaborating 😉

  4. Vincent Partington - Reply

    October 14, 2008 at 9:13 am

    Hey guys, thanks for that tip! I hadn't seen that option yet, but it seems an even easier solution to the problem. Especially when other people on your project don't have the setting I mentioned and reformat the code which removes the star again. (You know who you are! 😉 )

  5. Ron - Reply

    October 20, 2008 at 2:10 pm

    Great tip!
    cheers, Ron

  6. [...] idea taken from Tagged as: Eclipse, JUnit 4 Leave a comment Comments (0) Trackbacks (0) ( subscribe to [...]

  7. Janosch - Reply

    February 21, 2011 at 1:13 am

    Had been annoying me for a long while, and this is now over :-).

  8. Strangeoptics - Reply

    September 17, 2011 at 4:42 pm

    Exactly what I was searching for.

    I am Writing a Posting about Eclipse shortcuts and the drawback of organise imports.
    Best Of Short Cuts For Eclipse


  9. Shalom Shachne - Reply

    December 20, 2011 at 4:43 pm

    Thanks for posting all the tips. Very big help, and increased my productivity right away!

Add a Comment