JUnit – A Complete Java Unit Testing Example With Advance Features, Source Code and Diagram

This is a good and thorough tutorial for JUnit Testing I have written so far, where I have tried to accommodate most of the JUnit Features under one Test class and show that to you.

Also, I have written several other articles on JUnit. So don’t forget to read my articles on JUnit Best Practices, why you should use JUnit 4.0 instead of JUnit 3.0, how to performance test your JUnit Test Case, running JUnit as a Test Suite, understanding JUnit annotations¬†and an interesting article on Test Driven Development.

In this article, I aim to make the following stuffs clear when you go through this single post.

  1. Writing a JUnit Test Case
  2. Using JUnit Annotations:
    • @Test
    • @After
    • @Before
    • @AfterClass
    • @BeforeClass
    • @RunWith
    • @Parameter
  3. Performing one Time Setup
  4. Performing one Time TearDown
  5. Normal Setup for each Test Case
  6. Normal TearDown for each Test Case
  7. Exception Handling for expected results

The following JUnit sample test code is written and tested against 4.3.1 version of Junit. Note that there are two classes. MyStuff.java is a class with method which is going to be unit tested. MyStuffTest.java is the real JUnit Test class.

SIMPLE CLASS WHICH WILL BE UNIT TESTED:

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * This class is very simple class intended to be used by
 * JUnit Test Case for validating various stuffs.
 */
public class MyStuff {

	public double testMethodOne(int a, int b) {
		return a/b;
	}

}

Continue reading