Tags: , ,

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.

  2. @Before and @After
    Use @Before and @After annotations for “setup” and “tearDown” methods respectively. They run before and after every test case.

  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.

  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.

  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.
  6. Timeout
    Define a timeout period in miliseconds with “timeout” parameter. The test fails when the timeout period exceeds.

  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);

  8. JUnit4Adapter
    Run your Junit 4 tests in Junit 3 test runners with Junit4Adapter.

Happy coding. :D


RSS Feed

Digg It!

Add to Del.cio.us

Stumble It!

Add to Technorati Favorites

Add to Reddit

Related Posts

60 Responses to “JUnit 4 in 60 Seconds”


  1. 1 MJ

    Nice one, thanks!

  2. 2 westlakken

    sometimes I’m not sure if I really exist

  3. 3 Peter Andersen

    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

  4. 4 Abdullah Cetin CAVDAR

    Thanks for reminding the static imports Peter. :D

  5. 5 Stephen

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

    nice junit guide. appreciate!

  6. 6 BLK

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

  7. 7 Naveen

    Great way to explain in less time

  8. 8 timothy

    clear and concise explanation! thank you.

  9. 9 Aley Raza

    Nice tutorial

  10. 10 santhosh

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

  11. 11 Ulf Zibis

    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. 12 PeterK

    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. 13 Abdullah Cetin CAVDAR

    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. 14 Phani

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

  15. 15 Abdullah Cetin CAVDAR

    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. 16 Steven M. Armstrong

    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. 17 Eugen Plischke

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

  18. 18 Shikha

    Nice work.. thanks[:)]

  19. 19 cha

    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. 20 Abdullah Cetin CAVDAR

    @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. 21 sandeep

    –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. 22 sandeep

    –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. 23 Simone

    Very easy and useful!

    Thanx!

  24. 24 sandeep

    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. 25 Abdullah Cetin CAVDAR

    @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. 26 Mighty Chip

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

  27. 27 cha

    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. 28 Abdullah Cetin CAVDAR

    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. 29 cha

    Nice answer. It’s very useful to me.

    Thanks so much !

  30. 30 Ye Fu

    Very nice . Thanks

  31. 31 sk_svenska

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

  32. 32 Arvids

    Great one!

  33. 33 Mattias

    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. 34 Aparna

    Thank you for this fantastic short introduction to JUnit 4.

  35. 35 Dosha Kenkan

    very helpful, thanks

  36. 36 xcy666

    It’s good!
    Simple but clear

  37. 37 Jean-Claude

    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. 38 QAFE

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

  39. 39 Animated favicons

    Very nice . Thanks

  40. 40 Abdullah Cetin CAVDAR

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

  41. 41 Bob Carpenter

    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. 42 Raghavan alias Saravanan M

    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. 43 Gangadhar

    Nice one! Thank you very much!

  44. 44 MrBCut

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

  45. 45 paul

    nice one. especially point 8 saved my day

  46. 46 Andrew

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

  1. 1 JUnit 4 en 60 secondes | Le blog de David Loureiro
  2. 2 JUnit 4 em 60 Segundos « André Faria Gomes
  3. 3 Web und Netzwerk » Gute und schnelle Einführung in Java JUnit 4 Tests » Schweinfurt den ...
  4. 4 Gonow » Principais diferenças entre o JUnit 3.x e o 4.x
  5. 5 JUnit « Investigando ando
  6. 6 Unit Testing Exceptions with JUnit 4.5 Annotations « LingPipe Blog
  7. 7 Testing context for UrlRewrite and JUnit4
  8. 8 Breve recordatorio de lo visto estos días « El blog de Fran
  9. 9 android2's me2DAY
  10. 10 heartsavior's me2DAY
  11. 11 JUnit 4 Vs TestNG – Comparison | unittest
  12. 12 Gumtree Notes - » JUnit 4 Howto
  13. 13 Unit Test, JUnit, MockObject … « Pjin’s Blog
  14. 14 costumes

Leave a Reply




View Abdullah Çetin ÇAVDAR's profile on LinkedIn

Join My Community at MyBloglog!

Add to Technorati Favorites

Subscribe To My FriendFeed!

E-Mail Subscriptions

Enter your email address: