Skip to content


JUnit 4 in 60 Seconds

I played with JUnit 4 library this weekend and here is the short introduction to it:

  1. @Test
    Mark your test cases with @Test annotations. You don’t need to prefix your test cases with “test”.  In addition, your class does not need to extend from “TestCase” class.
    [source:Java]
    @Test
    public void addition() {
    assertEquals(12, simpleMath.add(7, 5));
    }

    @Test
    public void subtraction() {
    assertEquals(9, simpleMath.substract(12, 3));
    }
    [/source]

  2. @Before and @After
    Use @Before and @After annotations for “setup” and “tearDown” methods respectively. They run before and after every test case.
    [source:Java]
    @Before
    public void runBeforeEveryTest() {
    simpleMath = new SimpleMath();
    }

    @After
    public void runAfterEveryTest() {
    simpleMath = null;
    }
    [/source]

  3. @BeforeClass and @AfterClass
    Use @BeforeClass and @AfterClass annotations for class wide “setup” and “tearDown” respectively. Think them as one time setup and tearDown. They run for one time before and after all test cases.
    [source:Java]
    @BeforeClass
    public static void runBeforeClass() {
    // run for one time before all test cases
    }

    @AfterClass
    public static void runAfterClass() {
    // run for one time after all test cases
    }
    [/source]

  4. Exception Handling
    Use “expected” paramater with @Test annotation for test cases that expect exception. Write the class name of the exception that will be thrown.
    [source:Java]
    @Test(expected = ArithmeticException.class)
    public void divisionWithException() {
    // divide by zero
    simpleMath.divide(1, 0);
    }
    [/source]
  5. @Ignore
    Put @Ignore annotation for test cases you want to ignore. You can add a string parameter that defines the reason of ignorance if you want.
    [source:Java]
    @Ignore(“Not Ready to Run”)
    @Test
    public void multiplication() {
    assertEquals(15, simpleMath.multiply(3, 5));
    }
    [/source]
  6. Timeout
    Define a timeout period in miliseconds with “timeout” parameter. The test fails when the timeout period exceeds.
    [source:Java]
    @Test(timeout = 1000)
    public void infinity() {
    while (true)
    ;
    }
    [/source]
  7. New Assertions
    Compare arrays with new assertion methods. Two arrays are equal if they have the same length and each element is equal to the corresponding element in the other array; otherwise, they’re not.

    public static void assertEquals(Object[] expected, Object[] actual);
    public static void assertEquals(String message, Object[] expected, Object[] actual);

    [source:Java]
    @Test
    public void listEquality() {
    List expected = new ArrayList();
    expected.add(5);

    List actual = new ArrayList();
    actual.add(5);

    assertEquals(expected, actual);
    }
    [/source]

  8. JUnit4Adapter
    Run your Junit 4 tests in Junit 3 test runners with Junit4Adapter.
    [source:Java]
    public static junit.framework.Test suite() {
    return new JUnit4TestAdapter(SimpleMathTest.class);
    }
    [/source]

Happy coding. :D

Posted in TDD.

Tagged with , , .


97 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. MJ says

    Nice one, thanks!

    • java67 says

      Indeed fantastic tutorial , something for quick startup on JUnit4. I like the to the point explanation and example. By the way here is my list of Junit 4 annotations

  2. westlakken says

    sometimes I’m not sure if I really exist

  3. Peter Andersen says

    If the static import has been shown in 1. the example contain the full picture.

    import static junit.framework.Assert.*;

    or

    import static junit.framework.Assert.assertEquals;

    Good 60 sec. guide though

    /Peter

    • Arindam Chanda says

      Awesome guide..what simple examples.
      The import should be I thought:-
      import static org.junit.Assert.*

  4. Abdullah Cetin CAVDAR says

    Thanks for reminding the static imports Peter. :D

  5. Stephen says

    westlakken, maybe you are just someone else’s reflection.

    nice junit guide. appreciate!

  6. BLK says

    Nice… is great for me, and very easy, thanks..

  7. Naveen says

    Great way to explain in less time

  8. timothy says

    clear and concise explanation! thank you.

  9. Aley Raza says

    Nice tutorial

  10. santhosh says

    Hey appreciate yor help regarding this
    I am moved from a novice user to some kind of a basic user
    Once again thanks

  11. Ulf Zibis says

    Peter Andersen’s static imports are for JUnit 3.x library.

    Here we are in JUnit 4.x library, so we have to use:
    import static org.junit.Assert.*;

    I’m missing god example for parametrized tests.
    - can you add some ?
    - Do you know a good link ?

    -Ulf

  12. PeterK says

    Anyone here tried TestNG out? It extends on the idea of annotations and also provides a larger set of execution control annotations. It’s JUnit style so the learning curve should be small.
    Ulf:
    TestNG also supports parameterization.

  13. Abdullah Cetin CAVDAR says

    I heard lots of good comments about TestNG but I haven’t tried it yet unfortunately. If anyone tried it, we would be happy to read his/her thougths. :D

  14. Phani says

    When I am running with @Ignore tag, JUnit is not ignoring that test case.
    Please can you check back once again?

  15. Abdullah Cetin CAVDAR says

    I checked it once again Phani. It seems, @ignore is working as stated in the post. The ignored test is shown in the test case list, however it is not executed actually.

  16. Steven M. Armstrong says

    Great summary.
    Your site has been recommended at my workplace for those migrating from jUnit 3 to jUnit 4.

    Thanks for the good work!

  17. Eugen Plischke says

    took me more time to write this comment than to understand the jUnit 4.x approach, great overview, thanks! :)

  18. Shikha says

    Nice work.. thanks[:)]

  19. cha says

    Anyone can tell me how to run a group of test cases like Junit 3.x?
    For example, with Junit 3.x, I write a class to test all test cases in a package

    public static void main (String[] args) {
    junit.textui.TestRunner.run(suite());
    }

    public static Test suite () {
    TestSuite suite = new TestSuite(“package one”);

    suite.addTestSuite(Class1.class);
    suite.addTestSuite(Class2.class);
    // add more here …

    return suite;
    }

    How to do the same with Junit 4.x ?

    Thanks.

  20. Abdullah Cetin CAVDAR says

    @Cha
    Hi,
    we can use @RunWith and @Suite.SuiteClasses annotations. Below I try to give the source code for our example.

    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;

    @RunWith(Suite.class)
    @Suite.SuiteClasses({
    SimpleMathTest.class
    // add other classes here (comma separated)
    })
    public class AllTests {
    }

    For your example, the above code will be:

    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;

    @RunWith(Suite.class)
    @Suite.SuiteClasses({
    Class1.class,
    Class2.class
    })
    public class AllTestsCha {
    }

  21. sandeep says

    –below is my code but its not running can any one help me please.Error is :No tests found in TestAnnotation—-

    import static org.junit.Assert.*;
    import junit.framework.JUnit4TestAdapter;

    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;

    public class TestAnnotation {
    static Maths maths = null;
    public static void main(String[] args) {
    junit.textui.TestRunner.run(TestAnnotation.class);

    }

    public static junit.framework.Test suite() {
    return new JUnit4TestAdapter(TestAnnotation.class);
    }

    @Before
    public static void runBeforeEveryTest() {
    maths = new Maths();
    }

    @After
    public static void runAfterEveryTest() {
    maths =null;
    }

    @Test
    public static void add() {

    int x = maths.add(10, 10);
    assertEquals(21, x);
    }
    }

  22. sandeep says

    –for this example what should be there inside the class and how to make it run–

    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;

    @RunWith(Suite.class)
    @Suite.SuiteClasses({
    math.class,
    Maths.class
    })
    public class AllTestsCha {

    public static voidmain(String a[]){

    –what should be there here to run the test–
    }
    }

    –please help me am total new to junit–

  23. Simone says

    Very easy and useful!

    Thanx!

  24. sandeep says

    Hi all,
    can any one say in this example how to add multiple testcases to the suite as
    the class in
    return new JUnit4TestAdapter(TestAnnotation1.class)
    can accept only one testcase at a time but i had many testcases

    we have any thing like new JUnit4TestAdapter(TestAnnotation1.class,one.class,two.class)

  25. Abdullah Cetin CAVDAR says

    @sandeep

    Hi,
    I try to give an answer to your problem in my previous comment. I hope, it will help. You can send PM me if you want.

  26. Mighty Chip says

    Awesome tutorial!! Thanks so much! :) Makes moving up to 4.x a snap!

  27. cha says

    Hi,

    I have a question that do the test cases run in order or not?

    Ex: I have test class includes 3 cases (testMethod1, testMethod2, testMethod3)

    When running, I see sometimes they run in order

    testMethod1
    testMethod2
    testMethod3

    but sometimes is not (2,1,3 or 3,2,1 …). Since I’m using a data sharing between them so that I must assure they will be run in order. My real case is :

    testCreateUser() –> always make sure this case will run firstly

    These case will be fail or error if testCreateUser() did not run before:

    testGetUserByID()
    testEditUser()

    Anyone can help me to show how to make them run in order always? I’m using JUnit4.x

    Thanks a lot.

  28. Abdullah Cetin CAVDAR says

    Test cases are not run in any order and you cannot guarantee to run them in some specific order.

    You don’t need them run in any order and you must not infact. Because test case must be independent. It means, it must run successfully without dependent (data, condition etc.) of any other test case(s). This is an important feature of test cases.

    So, you have to setup your test case’s running condition before it runs, you check or test something (using asserts) and you leave your environment in its state before the setting up process. The setUp() and tearDown() methods (naming convention before the JUnit 4.x) is generally used for this purpose. Because they run before and after each test case. They are annotated as @Before and @After in JUnit 4.X as we mentioned.

    In your example, you can create a user in a method annotated with @Before and you delete that user in in another method annotated with @After. Therefore, you guarantee that you have a user that you exactly know in your system to test your other methods. It can be something like that:

    @Before
    public void initializeSystem() {
    // user: id, name, surname
    this.user = userDAO.createUser(1, “Foo”, “Bar”);
    }

    @Test
    public void getUserById() {
    User newUser = userDAO.findUserById(1);
    assertEquals(this.user.getName(), newUser.getName());
    assertEquals(this.user.getSurname(), newUser.getSurname());
    }

    @After
    public void cleanSystemState() {
    userDAO.deleteUser(this.user);
    }

    For the above example, you have to guarantee that createUser() and deleteUser() methods are running correctly of course.

    I hope, it gives the general approach of independent unit testing. Creating such an environment is not easy I know. However, when we try to test our system as isolated and independent as possible, we not only testing our system, we are improving our overall architecture without noticing it. So, we have well-defined, fully tested, ready to use components and interfaces. I think, this is what we try to achieve. :D

  29. cha says

    Nice answer. It’s very useful to me.

    Thanks so much !

  30. Ye Fu says

    Very nice . Thanks

  31. sk_svenska says

    Good?
    Simple and easy?(*^__^*)

  32. Arvids says

    Great one!

  33. Mattias says

    Thanks for a great (and quick) introduction to JUnit4. This is more or less the only information that is needed for a quick start.
    A short description and an example. GREAT!

  34. Aparna says

    Thank you for this fantastic short introduction to JUnit 4.

  35. Dosha Kenkan says

    very helpful, thanks

  36. xcy666 says

    It’s good!
    Simple but clear

  37. Jean-Claude says

    Hi,

    Great Job, Thank you, it has saved me the time to read through a lot of documents.

    I just have a remark to the point 7 (Arrays comparison):
    I’m using the version 4.5 of JUnit and the following methods:

    assertEquals(String message, Object[] expecteds,
    Object[] actuals)
    assertEquals(Object[] expecteds, Object[] actuals)

    are deprecated.

    The new methods are: assertArrayEquals(…)

  38. QAFE says

    Brilliant, having used 3.8.1 for quite some time, this artucle eased me into 4 easily. Thanx!

  39. Animated favicons says

    Very nice . Thanks

  40. Abdullah Cetin CAVDAR says

    @Jean-Claude
    I’ll update the post when I have some time. Thank you. :D

  41. Bob Carpenter says

    Thanks! This is just what I needed. I just wrote a bunch of regexes to munge our 3.8 tests into 4.5 format.

    I’m not convinced all the static imports and attributes are better than the old way of doing things, but I don’t want to innovate (or retrovate?) on style, so I’m going with the flow.

    The one thing I couldn’t get rid of is my old pattern for testing exceptions in a try/catch block with explicit failure method calls. The problem I have is that some of my tests set up something like a stream, read off what’s expected, then make sure you get an attempt to read past end of stream exception. Crucially, I don’t want the test to succeed if one of the earlier reads throws an exception. And after the exception, I want to test that the stream knows its empty and isn’t in some funky state.

    I wrote a blog entry about it with code, linking to this entry:

    http://lingpipe-blog.com/2009/02/03/unit-test-exception-junit-4-5-annotations/

  42. Raghavan alias Saravanan M says

    Nice article Indeed :) Thanks for the post.

    Btw, the template editor for the coding (java code) is provided by WordPress by default? If so what set of tags do u use? Can you help me out please?

    It would be great if you can send me an email :).

    Cheers,
    Raghavan alias Saravanan M.

  43. Gangadhar says

    Nice one! Thank you very much!

  44. MrBCut says

    Thank you! You are so cool for showing us noobs. :)

  45. paul says

    nice one. especially point 8 saved my day

  46. Andrew says

    I just went about converting 70 tests to JUnit 4, and this guide was very helpful, thank you.

  47. Arun Reddy says

    Very helpful, Thanks a lot for such a great tutorial.!

  48. Sumit Joglekar says

    Gr8 Tutorial…….found it very useful….
    Thank you very much. I’ll be converting all tutorials to jUnit4 now.

  49. Selim says

    I Love JUnit

  50. addicted_guy says

    thanks dude i appreciate your effort to show your knowledge keep it up :)

  51. DJ says

    Gr8 article… Really made my venture with Junit4 easy… :) .. Thanks

  52. Ravi Kumar Gupta says

    Nice guide.. thanks :)

  53. Swagatika says

    Very helpful article to learn JUnit 1.4 quickly. Loved it. Keep posting.:)

  54. Wegra says

    With just a few sentences and examples, it’s better than any other guides. Nice Job!!!
    I translated your post into Korean for my local programmers.

  55. Tuna says

    Actually, the @Test annotation works if the surrounding class is NOT derived from TestCase, so it’s either

    1) Continue to derive from TestCase and name your methods testX

    or

    2) No longer derive from TestCase and add @Test to your methods.

    But not both (except if you _really_ want to):

    http://stackoverflow.com/questions/1661623/not-able-to-execute-tests-with-test-annotation-when-my-test-extends-testcasejun

    So the phrase

    “In addition, your class does not need to extend from “TestCase” class.”

    should be:

    “In that case, your class SHOULD NOT extend from “TestCase” class.”

  56. testing says

    The subsequent time I read a weblog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my choice to learn, however I really thought youd have something fascinating to say. All I hear is a bunch of whining about one thing that you can repair for those who werent too busy searching for attention.

  57. yogesh says

    thanks….a lot…

  58. CP says

    good quick info.

  59. Anonymouns says

    This is really a nice 60sec tutorial for beginners.
    If anyone wants to go one step further and do more testing (mainly functional testing) with Junit then this also can be done quite easily.
    For more information refer http://apitestingwithjunit.blogspot.in/

  60. Java Experience says

    I have also played a lot with Junit 4 test case categories.
    One can create so many permutations and combinations using the category feature added in JUnit 4.

  61. mozilla firefox says

    I find it so inspiring that I’m not the only guy out there over the age of 20 who doesn’t know any of this!
    Time to learn *about all of it*.

  62. test website says

    I’m really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you modify it yourself? Either way keep up the excellent quality writing, it’s rare to see a great blog like this one nowadays

  63. christmas gifts says

    Hi there mates, pleasant piece of writing and good arguments commented at this place, I
    am truly enjoying by these.

  64. versace shirt says

    Very nice post. I just stumbled upon your weblog and
    wished to say that I have really enjoyed browsing your blog
    posts. In any case I will be subscribing to your
    rss feed and I hope you write again very soon!

  65. Gregory says

    I enjoy, lead to I discovered exactly what I used to be having a look for.
    You have ended my 4 day lengthy hunt! God Bless you man. Have
    a great day. Bye

  66. IT support in toronto says

    Excellent way of describing, and pleasant piece of writing to take facts concerning my presentation subject, which i am going to convey in college.

  67. SEO Technology says

    I know this web site gives quality dependent articles or reviews and other
    stuff, is there any other web site which gives these kinds of information in quality?

  68. Go to http://www.tdedballhot.com >> says

    Since the admin of this web page is working, no uncertainty very soon it will be well-known, due
    to its quality contents.

  69. more here says

    Hello, just wanted to mention, I loved this post. It was inspiring.
    Keep on posting!

Continuing the Discussion

  1. JUnit 4 en 60 secondes | Le blog de David Loureiro linked to this post on July 22, 2008

    [...] JUnit 4 in 60 Seconds présente les différentes annotations mises en place par JUnit 4 pour la [...]

  2. JUnit 4 em 60 Segundos « André Faria Gomes linked to this post on August 22, 2008

    [...] JUnit 4 em 60 Segundos Esse artigo que foi escrito por Abdullah Çetin ÇAVDAR em inglês, apresenta de forma simples e rápida como utilizar a nova API do JUnit. Veja também o artigo original. [...]

  3. Web und Netzwerk » Gute und schnelle Einführung in Java JUnit 4 Tests » Schweinfurt den ... linked to this post on September 20, 2008

    [...] testen von Java-Klassen und Methoden ablaufen erfährt man in dem englischsprachigen Tutorial auf cavdar.net in angeblich nur 60 Sekunden. Sehr empfehlenswert für alle Java Entwickler, die sich bisher nicht [...]

  4. Gonow » Principais diferenças entre o JUnit 3.x e o 4.x linked to this post on September 25, 2008

    [...] http://www.cavdar.net/2008/07/21/junit-4-in-60-seconds/ Alexandre Gandra (alexandre.gandra@gonow.com.br) [...]

  5. JUnit « Investigando ando linked to this post on January 23, 2009

    [...] JUnit 4 in 60 Seconds en cavdar.net [...]

  6. Unit Testing Exceptions with JUnit 4.5 Annotations « LingPipe Blog linked to this post on February 4, 2009

    [...] cavdar.net’s JUnit 4 in 60 Seconds [...]

  7. Testing context for UrlRewrite and JUnit4 linked to this post on March 12, 2009

    [...] the spirit of JUnit 4, where the test cases aren’t necessarily part of an inheritance hierarchy, as this article [...]

  8. Breve recordatorio de lo visto estos días « El blog de Fran linked to this post on March 14, 2009

    [...] JUnit 4 in 60 Seconds en cavdar.netTesting with JUnit en java.sun.com/developer/Books [...]

  9. android2's me2DAY linked to this post on March 26, 2009

    ?????? ??…

    JUnit 4 in 60 Seconds. That’s what I need!!! Nice Job!…

  10. heartsavior's me2DAY linked to this post on May 14, 2009

    Heart? ??…

    JUnit 4 in 60 Seconds ?… ?? +_+ ??? JUnit ? ?? ??… ;?; ?? ?? ?? ? ????…

  11. Gumtree Notes - » JUnit 4 Howto linked to this post on July 22, 2009

    [...] A good ‘60 second summary’ can be found here. [...]

  12. Unit Test, JUnit, MockObject … « Pjin’s Blog linked to this post on September 3, 2009

    [...] September 2, 2009 Unit Test, JUnit, MockObject … Posted by pjin under Uncategorized | Tags: JUnit; Unit Test | Leave a Comment  JUnit http://www.junit.org/home http://pub.admc.com/howtos/junit4x/ http://code.google.com/p/t2framework/wiki/JUnitQuickTutorial http://www.cavdar.net/2008/07/21/junit-4-in-60-seconds/ [...]

  13. costumes linked to this post on October 11, 2009

    costumes…

    an interesting take on a fun topic….

  14. Quick step-by-step guide : Upgrading Junit 3.x to Junit 4.x | bemoko's mobile web linked to this post on February 16, 2010

    [...] we finally got around to upgrade all our unit tests to Junit 4 so we can start benefit from the new features. About time [...]

  15. girl geek in training» Blog Archive » J-J-J-J-JUnit linked to this post on June 30, 2010

    [...] a JUnit 4. Thus, the extra credit was to rewrite the slide using the latest version. I found this helpful blog post that I wanted to share/remember for all eternity (or until JUnit 5 comes [...]

  16. JUnit 4 h?zl? kullan?m k?lavuzu | E. Basri Kahveci linked to this post on August 7, 2010

    [...] bir yaz? ama ?u adreste JUnit 4 üzerine çok güzel bir özet var. Okumak, ö?renmek [...]

  17. ??? eclipse 3.3 ??? junit4 « GD’s blog linked to this post on October 21, 2010

    [...] JUnit 4 in 60 Seconds [...]

  18. Tech » JUnit4 Test Suite with Groovy and IntelliJIDEA linked to this post on November 6, 2010

    [...] This post illustrate how to create one Test Suite for JUnit4. Focusing on one Groovy (Groovy++) project under IntelliJIDEA (version 9.0 on this case). First, a little intro about Groovy and JUnit, in case you want (you should) learn more about it. Groovy have his own Test Case class, however to use JUnit4 you should leave this class behind, because she is more focused on JUnit 3 style, you can check more information about JUnit4 and Groovy here. Another very nice source to start with JUnit4 on JUnit 4 in 60 Seconds. [...]

  19. JUnit4 Test Suite with Groovy and IntelliJIDEA linked to this post on November 7, 2010

    [...] First, a little info about Groovy and JUnit, in case you want (you should) learn more about it. Groovy have his own Test Case class, however to use JUnit4 you should leave this class behind, because she is more focused on JUnit 3 style, you can check more information about JUnit4 and Groovy here. Another very nice source to start with JUnit4 here: JUnit 4 in 60 Seconds. [...]

  20. Bug Inside » Blog Archive » JUnit 4, 60??? ??? linked to this post on July 3, 2011

    [...] ??: JUnit 4 in 60 Seconds [...]

  21. Why write unit tests? « dev_religion linked to this post on June 14, 2012

    [...] your a Java dev, here’s a great 60 second tutorial to start you off in JUnit 4. Share this:Like this:LikeBe the first to like this. This entry was posted in [...]

  22. FlexUnit 4 in 360 seconds | Digital Primates linked to this post on January 12, 2013

    [...] a year back I remember reading a blog post called JUnit in 60 seconds. At the time I pondered how great it would be to have these features in Flex. Little did I know [...]



Some HTML is OK

or, reply to this post via trackback.