I played with JUnit 4 library this weekend and here is the short introduction to it:
- @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.@Test
public void addition() {
assertEquals(12, simpleMath.add(7, 5));
}@Test
public void subtraction() {
assertEquals(9, simpleMath.substract(12, 3));
} - @Before and @After
Use @Before and @After annotations for “setup” and “tearDown” methods respectively. They run before and after every test case.@Before
public void runBeforeEveryTest() {
simpleMath = new SimpleMath();
}@After
public void runAfterEveryTest() {
simpleMath = null;
} - @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.@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
} - 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.@Test(expected = ArithmeticException.class)
public void divisionWithException() {
// divide by zero
simpleMath.divide(1, 0);
} - @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.
@Ignore(“Not Ready to Run”)
@Test
public void multiplication() {
assertEquals(15, simpleMath.multiply(3, 5));
} - Timeout
Define a timeout period in miliseconds with “timeout” parameter. The test fails when the timeout period exceeds.@Test(timeout = 1000)
public void infinity() {
while (true)
;
} - 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);@Test
public void listEquality() {
Listexpected = new ArrayList ();
expected.add(5);List
actual = new ArrayList ();
actual.add(5);assertEquals(expected, actual);
} - JUnit4Adapter
Run your Junit 4 tests in Junit 3 test runners with Junit4Adapter.public static junit.framework.Test suite() {
return new JUnit4TestAdapter(SimpleMathTest.class);
}
Happy coding.

Nice one, thanks!
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
sometimes I’m not sure if I really exist
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
Awesome guide..what simple examples.
The import should be I thought:-
import static org.junit.Assert.*
Thanks for reminding the static imports Peter.
westlakken, maybe you are just someone else’s reflection.
nice junit guide. appreciate!
Nice… is great for me, and very easy, thanks..
Great way to explain in less time
clear and concise explanation! thank you.
Nice tutorial
Hey appreciate yor help regarding this
I am moved from a novice user to some kind of a basic user
Once again thanks
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
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.
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.
When I am running with @Ignore tag, JUnit is not ignoring that test case.
Please can you check back once again?
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.
Great summary.
Your site has been recommended at my workplace for those migrating from jUnit 3 to jUnit 4.
Thanks for the good work!
took me more time to write this comment than to understand the jUnit 4.x approach, great overview, thanks!
Nice work.. thanks[:)]
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.
@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 {
}
–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);
}
}
–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–
Very easy and useful!
Thanx!
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)
@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.
Awesome tutorial!! Thanks so much!
Makes moving up to 4.x a snap!
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.
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.
Nice answer. It’s very useful to me.
Thanks so much !
Very nice . Thanks
Good?
Simple and easy?(*^__^*)
Great one!
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!
Thank you for this fantastic short introduction to JUnit 4.
very helpful, thanks
It’s good!
Simple but clear
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(…)
Brilliant, having used 3.8.1 for quite some time, this artucle eased me into 4 easily. Thanx!
Very nice . Thanks
@Jean-Claude
I’ll update the post when I have some time. Thank you.
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/
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.
Nice one! Thank you very much!
Thank you! You are so cool for showing us noobs.
nice one. especially point 8 saved my day
I just went about converting 70 tests to JUnit 4, and this guide was very helpful, thank you.
Very helpful, Thanks a lot for such a great tutorial.!
Gr8 Tutorial…….found it very useful….
Thank you very much. I’ll be converting all tutorials to jUnit4 now.
I Love JUnit
thanks dude i appreciate your effort to show your knowledge keep it up
Gr8 article… Really made my venture with Junit4 easy…
.. Thanks
Nice guide.. thanks
Very helpful article to learn JUnit 1.4 quickly. Loved it. Keep posting.:)
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.
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.”
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.
thanks….a lot…
good quick info.
Thx.
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/
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.
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*.
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
Thank you for your nice comments.
Meanwhile, I use the Carrington Blog free WP theme. I do not modify it much. http://carringtontheme.com/themes/
Hi there mates, pleasant piece of writing and good arguments commented at this place, I
am truly enjoying by these.
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!
Thanks.
I’m thinking of starting to write again. Stay updated.
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
Excellent way of describing, and pleasant piece of writing to take facts concerning my presentation subject, which i am going to convey in college.
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?
Since the admin of this web page is working, no uncertainty very soon it will be well-known, due
to its quality contents.