JUNIT is an open-source testing framework for java programmers.

The java program
mer can create test cases and test his/her own code.
It is one of the unit testing framework. Current version is junit 4.
To perform unit testing, we need to create test cases. The unit test case is a c
ode which ensures that the program logic works as expected.
The org.junit package contains many interfaces and classes for junit testing suc
h as Assert, Test, Before, After etc.
Annotations for Junit testing
The Junit 4.x framework is annotation based, so let's see the annotations that c
an be used while writing the test cases.
@Test annotation specifies that method is the test method.
@Test(timeout=1000) annotation specifies that method will be failed if it takes
longer than 1000 milliseconds (1 second).
@BeforeClass annotation specifies that method will be invoked only once, before
starting all the tests.
@Before annotation specifies that method will be invoked before each test.
@After annotation specifies that method will be invoked after each test.
@AfterClass annotation specifies that method will be invoked only once, after fi
nishing all the tests.
Assert class
The org.junit.Assert class provides methods to assert the program logic.
Methods of Assert class
The common methods of Assert class are as follows:
void assertEquals(boolean expected,boolean actual): checks that two primitives/o
bjects are equal. It is overloaded.
void assertTrue(boolean condition): checks that a condition is true.
void assertFalse(boolean condition): checks that a condition is false.
void assertNull(Object obj): checks that object is null.
void assertNotNull(Object obj): checks that object is not null.
package com.java.logic;
public class Calculation {
public static int findMax(int arr[]){
int max=0;
for(int i=1;i<arr.length;i++){
if(max<arr[i])
max=arr[i];
}
return max;

} return max.junit.Assert. public class Calculation { public static int findMax(int arr[]){ int max=arr[0]. } //method that returns reverse words public static String reverseWord(String str){ StringBuilder result=new StringBuilder().length.java.-2})).findMax(new int[]{1. import static org.-4.4.3.java.javatpoint. for(int i=1. assertEquals(-1.i<arr.Calculation. import com.-1. } } -------------------------package com.findMax(new int[]{-12. StringTokenizer tokenizer=new StringTokenizer(str.Test. public class TestLogic { @Test public void testFindMax(){ assertEquals(4. public class Calculation { //method that returns maximum number public static int findMax(int arr[]){ int max=0. } //method that returns cube of the given number public static int cube(int n){ return n*n*n.Calculation.2})).hasMoreTokens()){ .length.junit.java.i++){ if(max<arr[i]) max=arr[i].logic." ").i<arr.*.} } --------------------package com.i++){ if(max<arr[i]) max=arr[i].logic.testcase.//arr[0] instead of 0 for(int i=1.*. } } ----------------------package com. import org.-3. } return max. while(tokenizer.logic.

} } --------------------Write the test case package com.toString().println("before class").AfterClass.junit. import import import import import import import static org.BeforeClass. org. assertEquals(4.append(tokenizer.testcase.4. assertEquals("ym eman si nhoJ".Calculation. assertEquals(-2.Before.Calculation. public class TestCase2 { @BeforeClass public static void setUpBeforeClass() throws Exception { System. org.junit.junit.println("test case cube"). org. assertEquals(27.java.nextToken()).StringBuilder sb=new StringBuilder().Calculation.out. org.Calculation. } return result.junit.Assert.-4.2})). } @Test public void testCube(){ System.-2})).out.findMax(new int[]{1.reverseWord("my name is John" ).javatpoint. } @Test public void testReverseWord(){ System. sb.out.-3.junit.Test.println("test case find max").3.After.Calculation. com. } @Before public void setUp() throws Exception { System.out. } .cube(3)). sb. } @After public void tearDown() throws Exception { System.println("after").append(sb). } @Test public void testFindMax(){ System.assertEquals.reverse(). org.println("test case reverse word").println("before").out.append(" ").out.logic. result. result.junit.findMax(new int[]{-12.

println("after class"). Let's check one example import junit.junit. } } ----------------------Features of JUnit Test Framework JUnit test framework provides the following important features Fixtures Test suites Test runners JUnit classes Fixtures Fixtures is a fixed state of a set of objects used as a baseline for running tes ts. which runs before every test invocation.Suite.out. both @RunWith and @Suite annotation are used to run the suite test. value2 = 3. which runs after every test method. } } Test Suites A test suite bundles a few unit test cases and runs them together.@AfterClass public static void tearDownAfterClass() throws Exception { System. tearDown() method. import org. import org. Given below is an example that uses TestJunit1 & TestJunit2 test classes.class) .runners.*.framework. public class JavaTest extends TestCase { protected int value1. The purpose of a test fixture is to ensure that there is a well-known and fixed environment in which tests are run so that results are repeatable. // assigning the values protected void setUp(){ value1 = 3. assertTrue(result == 6).RunWith. value2.junit. In JUnit.runner. } // test method to add two values public void testAdd(){ double result = value1 + value2. It includes setUp() method. //JUnit Suite Test @RunWith(Suite.

public class TestJunit2 { String message = "Robert". import org. import org.class).Assert.salutationMessage()).out.Result.runner. } } Test Runners Test runner is used for executing the test cases.junit. messageUtil.toString()).junit.out. assertEquals(message. assertEquals(message.class . static org.assertEquals.Failure.assertEquals.junit. public class TestRunner { public static void main(String[] args) { Result result = JUnitCore. @Test public void testPrintMessage() { System. MessageUtil messageUtil = new MessageUtil(message).messageUtil.println("Inside testSalutationMessage()"). org.out. MessageUtil messageUtil = new MessageUtil(message).junit. message = "Hi!" + "Robert".out.runClasses(TestJunit.runner. import static org.println(result.junit.junit.Assert.Ignore. import org.junit. for (Failure failure : result. public class TestJunit1 { String message = "Robert". Here is an example that assume s the test class TestJunit already exists. } } import org.TestJunit2.class }) public } import import import class JunitTestSuite { org.junit. import org.SuiteClasses({ TestJunit1.notification.JUnitCore.Test.getFailures()) { System.@Suite.Ignore.println("Inside testPrintMessage()").junit.println(failure. } } JUnit Classes . @Test public void testSalutationMessage() { System. } System.Test.runner.wasSuccessful()).printMessage()).

TestCase . used in writing and testing JUnits. private int age.Contains a set of assert methods.Contains methods to collect the results of executing a test case. } /** * @param monthlySalary the monthlySalary to set */ public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary. } /** * @param age the age to set */ public void setAge(int age) { . TestResult . } /** * @param name the name to set */ public void setName(String name) { this. ---------------------public class EmployeeDetails { private String name. } /** * @return the age */ public int getAge() { return age. Some of the important classes are Assert .name = name. /** * @return the name */ public String getName() { return name. } /** * @return the monthlySalary */ public double getMonthlySalary() { return monthlySalary.Contains a test case that defines the fixture to run multiple tests. private double monthlySalary.JUnit classes are important classes.

notification. } } import org.0).setAge(25).runner. }else{ appraisal = 1000. import org. yearlySalary = employeeDetails. .setMonthlySalary(8000). salary.junit. employee.junit. import static org.junit.this.getMonthlySalary() < 10000){ appraisal = 500.calculateAppraisal(employee). 0.0).junit. assertEquals(96000. employee. assertEquals(500. EmployeeDetails employee = new EmployeeDetails(). return yearlySalary.runner.calculateYearlySalary(employee). 0.junit. public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic().age = age.Failure. if(employeeDetails. employee. double appraisal = empBusinessLogic.assertEquals. } // test to check yearly salary @Test public void testCalculateYearlySalary() { employee. import org.runner.setName("Rajeev"). employee.setMonthlySalary(8000).Test. appraisal. } } import org.Assert. } return appraisal. double salary = empBusinessLogic. } // Calculate the appraisal amount of employee public double calculateAppraisal(EmployeeDetails employeeDetails) { double appraisal = 0.JUnitCore.setAge(25). //test to check appraisal @Test public void testCalculateAppriasal() { employee.Result.setName("Rajeev").getMonthlySalary() * 12. } } public class EmpBusinessLogic { // Calculate the yearly salary of employee public double calculateYearlySalary(EmployeeDetails employeeDetails) { double yearlySalary = 0.

.runner. Create your test case(s) using the instance variables as the source of the test data. static org. org. } } return true. private Boolean expectedResult.junit.toString()).runners.junit.runners.junit.class).assertEquals.getFailures()) { System. org.runClasses(TestEmployeeDetails.util.out.class). import org.RunWith. public class PrimeNumberChecker { public Boolean validate(final Integer primeNumber) { for (int i = 2. } } import java. There are five steps that you need to follow to create a parameterized test. Create an instance variable for each "column" of test data.wasSuccessful()). @RunWith(Parameterized.println(failure.Assert. import java. for (Failure failure : result.Parameterized.Parameterized. i < (primeNumber / 2).junit.Test.util.junit. i++) { if (primeNumber % i == 0) { return false. Create a public static method annotated with @Parameters that returns a Collecti on of Objects (as Array) as test data set. } } ---------------parameterized tests. import org.Collection.Before.out.class) public class PrimeNumberCheckerTest { private Integer inputNumber.junit.Arrays. } System. Annotate test class with @RunWith(Parameterized. Create a public constructor that takes in what is equivalent to one "row" of tes t data.Parameters. import import import import org.public class TestRunner { public static void main(String[] args) { Result result = JUnitCore. private PrimeNumberChecker primeNumberChecker.println(result. Parameterized tests allow a developer to run the same test over and over again using different values.

import org. true } }).runClasses(PrimeNumberCheckerTest. } @Parameterized.class).out.junit.asList(new Object[][] { { 2. public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.validate(inputNumber)).java in C:###BOT_TEXT###gt;JUNIT_WORKSPACE to execute test case(s).toString()). import org. { 23.println(failure. this. } } --------------------- . } // This test will run 4 times since we have 5 parameters defined @Test public void testPrimeNumberChecker() { System.junit. Boolean expectedResult) { this. { 22. { 6.wasSuccessful()). import org. primeNumberChecker.JUnitCore.runner.Result.expectedResult = expectedResult. } } Create Test Runner Class Create a java class file named TestRunner. { 19.runner.println("Parameterized Number is : " + inputNumber). } // Each parameter should be placed as an argument here // Every time runner triggers. true }. false }. assertEquals(expectedResult.println(result.getFailures()) { System.Parameters public static Collection primeNumbers() { return Arrays.out.runner.@Before public void initialize() { primeNumberChecker = new PrimeNumberChecker(). for (Failure failure : result. } System.Failure. false }. true }. it will pass the arguments // from parameters we defined in primeNumbers() method public PrimeNumberCheckerTest(Integer inputNumber.inputNumber = inputNumber.notification.out.junit.