MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Introduction to JUnit - an open source unit test framework for Java

In this article we will discuss Junit and its implementation in java.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction

JUnit is an open source unit test framework for Java programming language. It is a useful for both types of developers who use the test driven development (TDD) methodology and who don't use TDD. JUnit is a part of the unit testing framework family - xUnit. JUnit not only increases the productivity of the developer but also increases the stability of the program. If each of the methods of a class are unit tested with all possible test data, there is a very less that the code will produce any defect or bug. In the modern era, where every project is challenging in all aspects, JUnit has become an essential part of day to day development. Many customers want their applications to be developed in test driven development environment.

Why JUnit is essential?

A stand alone java program is tested or executed via its main method which is not a full proof methodology as it has its limitation when it comes to test all the flows of a complex program. Moreover in a web based application where there are different tiers, each and every tier has to be unit tested before the functional test starts. Some of the limitations in testing a program via its main method are :

  • Testing via main doesn't have a concept of pass or fail. Developers use debug statements (System.out.println) to actually check the result of the program.
  • There is no mechanism to collect the results in a structured fashion.
  • After each run the developer has to manually check the results.

Advantages of JUnit

  • In a web based application, JUnit is mainly used to test the DAO layer as these classes can be executed without any application server.
  • We can test Struts/Spring based application also. At times service classes are also tested using JUnits.
  • With the help mocked objects, (jmock framwork) JUnit helps a developer to test the different tiers of the application even when the tiers are not integrated, thus Junit helps to identify the defects at a much earlier stage.
  • Application server is not required in order to execute a JUnit test case.

Features of JUnit

  • JUnit is an open source framework used for writing & executing unit test cases.
  • JUnit identifies the test methods using annotations.
  • JUnit tests the expected results using the assert method.
  • JUnit helps in faster development with increased quality.
  • JUnit is simple and can be developed in less time.
  • JUnit tests can be run automatically. These tests check their own results and provide immediate feedback. These tests can also be organized into test suites consisting of multiple test cases.
  • Junit shows the result in a progress bar. This bar is green if test is goes fine and it turns red when a test fails.
  • Junit can easily be integrated with standard IDEs e.g. eclipse, netbeans etc.

Setting up JUnit and run a simple program

JUnit comes as a packaged jar library. It can be downloaded from - http://junit.org/. The following jar files needs to be downloaded -

  • junit.jar
  • hamcrest-core.jar

Setting up Junit in eclipse is prett easy. Follow the following steps in order to set up JUnit on eclipse:

  • Create a java project say Junit in eclipse
  • Eclipse creates a source folder - src by default. Create another source folder - tests. This folder will store the Junit classes while the src folder would store the java classes. Create another folder - lib. This folder would store the above mentioned two jar files and any other jar file required in the project.
  • Create the package - com.home.junit within each of the source folders - src & tests.
  • Add a java file - SampleAdd under src. Within this add a method to add two integers.

Add another java file - SampleAddTest within test.

Listing 1: The sample class defines a Java class to be used

 - The Java class
		package com.home.junit;

		public class SampleAdd {
	
			public int add(int x, int y) {
				return x + y;
			}
		}

Listing 2: The sample class shows the usage of junit

 - The JUnit class
		package com.home.junit;

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

		public class SampleAddTest  {
	
			private SampleAdd sampleClass;
	
			@Before
			public void setUp() {
				sampleClass = new SampleAdd();
			}
	
			@Test
			public void testAdd() {
				Assert.assertEquals(5, sampleClass.add(3, 2));
				Assert.assertEquals(-1, sampleClass.add(-3, 2));
				Assert.assertNotEquals(5, sampleClass.add(3, 3));
			}
	
			@After 
			public void settleDown() {
				sampleClass = null;
			}
		}

In eclipse, the project should look like as under:

A sample Junit project in eclipse.

Figure 1: A sample Junit project in eclipse.

On eclipse a Junit test program can be executed via 'Right click -> Run as -> Junit Test'

Junit and Annotation

Since version 4.x, JUnit uses the annotation feature of java in a much efficient manner. A developer donot have to explicitly extend his test class to junit.framwork.Testcase. The following annotations are used in junit :

Annotations Description
@Testpublic void method () Identifies that a method is a test method
@Beforepublic void method () This executes prior to the execution of each test method. Used for initialising the objects required for the execution of the test method.
@Afterpublic void method () This executes after the execution of each test method. Used for releasing the objects which were initialised in the @Before method.
@BeforeClass public static void method() This method is executed once, before the start of all tests. This can be used to perform activities like connect to a database, load properties file etc. Methods using this annotation need to be defined as static to work with JUnit.
@AfterClass public static void method() This method is executed once, after all the tests are executed. This can be used to perform activities like close the DBConnection, relese other stream resources etc. Methods using this annotation need to be defined as static to work with JUnit.
@Ignore Used to indicate that the test method would be ingnored. Very useful in the test driven development methodology.
@Test (expected = Exception.class) Fails if the method under test doesn't throw the said exception.
@Test(timeout=100) Fails if the method doesnot responds within 100 msecs.

Table 1 - list of annotaions and their meanings

Assertions

The Assert class in JUnit is responsible to run the test cases. It has the following static methods:

Test methods Description
fail(String) Let the method fail. Used to check if a certain part of the code is not reached. Usefull for TDD as it fails before the test code ins implemented.
assertTrue([message], boolean condition) Checks whether the boolean condition is true.
assertsEquals([String message], expected, actual) Checks that two values are the same.
assertsEquals([String message], expected, actual, tolerance) Checks whether two float or double values are same. Tolerance is the number of decimals which should be the same.
assertNull([message], object) Checks if the object is null.
assertNotNull([message], object) Checks if the object is not null.
assertSame([String], expected, actual) Checks if both variables refer to the same object.
assertNotSame([String], expected, actual) Checks if both variables refer to different objects.

Table 2 - list of assertion methods and their meanings

Test Suite

Consider the scenario where there are multiple test cases and all of them needs to be executed in one go. These test methods can be combined into a single test suite. Once the test suite is executed, it will run all the test cases in one shot.

Conclusion

Junit is a unit test framework for java developers. It helps to identify the defects in the intial stage of development. It is very useful in environment where TDD is followed. Test cases executes via the different assert methods. Multiple test cases can be clubbed into one single test suite.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login