JUnit Tutorial

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks. Its main use is to write repeatable tests for your application code units.

Installation

To include JUnit into your project, you need to include its dependency into classpath.

  • JUnit Maven Dependency

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    
  • JUnit Gradle Dependency

  • dependencies {
      testCompile 'junit:junit:4.12'
    }
    
  • JUnit Jar File

    Click the link to download JUnit 4.12 jar file.

JUnit Annotations

JUnit offers following annotations to write tests.

AnnotationDescription
@BeforeThe annotated method will be run before each test method in the test class.
@AfterThe annotated method will be run after each test method in the test class.
@BeforeClassThe annotated method will be run before all test methods in the test class. This method must be static.
@AfterClassThe annotated method will be run after all test methods in the test class. This method must be static.
@TestIt is used to mark a method as junit test
@IgnoreIt is used to disable or ignore a test class or method from test suite.
@FixMethodOrderThis class allows the user to choose the order of execution of the methods within a test class.
@RuleAnnotates fields that reference rules or methods that return a rule.
@ClassRuleAnnotates static fields that reference rules or methods that return them.

Writing Tests in JUnit

In JUnit, test methods are marked with @Test annotation. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure. If no exceptions are thrown, the test is assumed to have succeeded.

import java.util.ArrayList;

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

public class Example {
	@BeforeClass
	public static void setup() {
	}

	@Before
	public void setupThis() {
	}

	@Test
	public void method() {
		org.junit.Assert.assertTrue(new ArrayList().isEmpty());
	}

	@After
	public void tearThis() {
	}

	@AfterClass
	public static void tear() {
	}
}

Test Suites

Using JUnit test suites, you can run tests spread into multiple test classes. In JUnit, both @RunWith and @Suite annotations are used to run the suite tests.

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

@RunWith(Suite.class)

@Suite.SuiteClasses({
   TestJunit1.class,
   TestJunit2.class
})

public class JunitTestSuite {   
}  

Assertions

Assertions help in validating the expected output with actual output of a testcase. All the assertions are in the org.junit.Assert class. All assert methods are static, it enable better readable code.

import static org.junit.Assert.*;

@Test
public void method() {
	assertTrue(new ArrayList().isEmpty());
}

Assumptions

Assumption indicate the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information. Assume basically means “don’t run this test if these conditions don’t apply”. The default JUnit runner skips tests with failing assumptions.

import org.junit.Test;
import static org.junit.Assume.*;


public class Example {
	public class AppTest {
	    @Test
	    void testOnDev() 
	    {
	        System.setProperty("ENV", "DEV");
	        assumeTrue("DEV".equals(System.getProperty("ENV")));
	    }
	     
	    @Test
	    void testOnProd() 
	    {
	        System.setProperty("ENV", "PROD");
	        assumeFalse("DEV".equals(System.getProperty("ENV")));  
	    }
	}
}

Conclusion

JUnit is undoubtedly most used and robust unit testing framework in java technologies. It has easy learning curve and simple to follow coding practices. Most of IDEs have in-built support for junit tests execution within IDE itself and that make it more developer friendly.

Reference:

JUnit Documentation

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

11 thoughts on “JUnit Tutorial”

  1. You are doing a wonderful job on tutorial. (This is coming from a non-java background developer who has just putting her hand on java and understood your tutorial right away).

    Please be aware to fix your typo on Parametrized testcases with junit 4 line 16:
    public static Iterable data()
    really should be
    public static Iterable data() //with no space in between “Object” and “[]” and “object” should be upper case “O”

    These type of typo isn’t a problem with native Java devs, but for someone who’s not native to Java syntax can be a big problem for trying out your tutorials.

    Good job and please keep it up. I’m looking forward for more fancy ways to play with Junit =)

  2. Hi

    I created one J table.In that J table having the two columns
    1) Account Number
    2) Account Name
    3) Actions .It is also the column name.but am not doing any sorting in that filed.In that action column there is one icon with taht icon i can delete the records.
    And the below there are two fileds.The field names are
    Account Number :
    Account Name:
    The button name is “ADD”.On click of add button that data should comes into my table.

    Actually my question is iam displaying the plain jtable.So first i want display the data in the table.That data should from DB.
    After displaying the data how can we add the rows.and how to delete those rows on click of that icon ?
    This is my question.Could you please help to finish this task

    Thanks in Advance

    Sri

  3. Hi Lokesh,

    Can you write article for best practices of doing exception handling for struts1.x based and spring mvc based applications

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.