Home > Uncategorized > Junit Tutorial with examples

Junit Tutorial with examples

Junit is one the most popular unit testing framework around .  This tutorial will help you in getting started with Junit setup on eclipse with some code examples . The Junit tutorial is structured as follows

  • Introduction
    • About Unit testing tools
    • About JUnit
    • For first time developers
  • Inside JUnit
    • JUnit API’s
  • Settings to be done in eclipse for JUnit
  • Sample Codes
    • Sample Java Calculation Engine.
    • Sample JUnit code to run in GUI mode.
    • Sample JUnit code to run in text mode (CLI – command line).
      • JUnit Execution procedure
        • Execution in GUI mode.
        • Execution in Text mode.
      • JUnit Links and References.
      • Conclusion

Introduction:

  • About Unit testing
    • Process of software life cycle
    • Should be done while coding
    • Unit testing tools: C++ Unit, JUnit, OUnit (for PL/SQL), HTTPUnit and So on.
    • Assert the correctness of code by Expected result vs. the runtime resultusing the unit testing tools.Unit testing tools are used to test the Method/Stored procedure we havewritten. We know the return result of the particular method we wrote andexpect the same results from the method. Then we have to assert (methodresult and expected result) which will help u to match our code and ourexpectation/requirement.
  • About JUnit
    • It is an instance of the xUnit architecture for unit testing frameworks
    • Plug-in for unit testing in java.
    • Executed in both GUI and Text mode.
    • Easy to generate JUnit test cases and JUnit test suite.
  • For first time developers
    • Follow the Settings to be done in eclipse for JUnit.
    • Try with the sample codes.

Inside JUnit:

JUnit API’s:

Methods inherited from class junit.framework.Assert
assertEquals, assertFalse, assertNotNull,

assertNotSame, assertNull, assertSame, assertTrue,

For More information on API’s refer JUnit reference.

Settings to be done in eclipse for JUnit:

Select junit.jar into the java build path

Eclipse For JUnit Sample

Figure shows the selection of the junit.jar into the java build path.

Follow these steps for the above process:

File -> Properties -> Java Build Path -> Libraries -> Add External JARs -> and Select the junit.jar

from your local directory and click on OK.

Sample Codes:

Steps to create the sample code:

  1. Create a project JUnit Samples.
  2. Select the JUnit.jar into the java build path (Refer: Settings to be done in eclipse for JUnit).
  3. Create the Calculation.java in src->Engine
  4. Create the CalculationTest.java in src->TestEngine
  5. Set the Default output folder (JUnit Samples -> Properties -> Java Build Path -> Default Output Folder).

Sample Java Calculation Engine:

Program Name: Calculation.java.

package Engine;

/**

* This class is the sample test class.

*/

public class Calculation {

int add(int value1, int value2) {

return value1 + value2;

}

int subtract(int value1, int value2) {

return value1 – value2;

}

int multiply(int value1, int value2) {

return value1 * value2;

}

int divide(int value1, int value2) {

return value1 / value2;

}

}

Sample JUnit code to run in GUI mode.

Steps to create the JUnit code to run in GUI mode:

  1. Java Browsing -> Types -> Select a class for which u wants to create JUnit class ->
    New -> JUnit Test CaseJUnit GUI Mode

    Figure shows the selection of JUnit Test Case creation.

  2. Select a package name for JUnit test class, JUnit class name, the method stubs and the
    Class to test.

    JUnit Test Case

    Figure shows the selection of Package/Stubs to generate the JUnit test case.

  3. Select the methods for which u need the JUnit methods.New JUnit Test Case
    Figure shows the selection of method names to generate JUnit test case.Following JUnit code will be generated by the eclipse.Program Name: CalculationTest.java.

    package TestEngine;

    import junit.framework.TestCase;

    public class CalculationTest extends TestCase {

    private Calculation calcEngine;

    /**

    * For initializing the values.

    * Initialization of the variables can be done here.

    */

    protected void setUp() throws Exception {

    super.setUp();

    }

    /**

    * For cleaning the values.

    * Dereference/Uninitialization/freeing memory can be done here.

    */

    protected void tearDown() throws Exception {

    super.tearDown();

    }

    /**

    * Constructor for CalculationTest.

    * @param arg0

    */

    public CalculationTest(String arg0) {

    super(arg0);

    calcEngine = new Calculation();

    }

    // test case method name should start with test.

    public final void testAdd() {

    assertEquals(calcEngine.add(20, 30), 50);

    }

    // test case method name should start with test.

    public final void testSubtract() {

    assertEquals(calcEngine.subtract(60, 30), 30);

    }

    // test case method name should start with test.

    public final void testMultiply() {

    assertEquals(calcEngine.multiply(100, 3), 300);

    }

    // test case method name should start with test.

    public final void testDivide() {

    assertEquals(calcEngine.divide(333, 3), 111);

    try {

    assertEquals(calcEngine.divide(100, 0), 20);

    } catch (Exception e) {

    // Exception is expected so asserting for true.

    assertTrue(true);

    }

    }

    Sample JUnit code to run in text mode (CLI – command line).

    Add this code to the CalculationTest.java to run in CLI.

    public static void main(String[] args) {

    junit.textui.TestRunner.run(CalculationTest.suite());

    }

    private static TestSuite suite() {

    TestSuite suite = new TestSuite(“Test for Engine.Calculation.java”);

    //$JUnit-BEGIN$

    suite.addTestSuite(CalculationTest.class);

    //$JUnit-END$

    return suite;

    }

JUnit Execution procedure:

  1. Run the JUnit code in GUI mode using Debug JUnit Test/ Run JUnit Test.
  2. Run the JUnit code in Text mode using Debug Java Application/ Run Java Application.

Debug JUnit Test

Select the JUnit file -> Select Run -> Select Debug JUnit Test.

Execution in GUI mode:

Result in colors:

RED indicates the execution failed (even if anyone of the test case fails).

GREEN indicates the execution is successful. Execution in Text mode:

JUnit Color Result

Execution in Text mode:

JUnit Text Mode

Conclusion:

An advantage of Unit testing tools is whenever the source code changes we can test the functionality of the modified source code without changing the JUnit test cases. HTTPUnit is used for unit testing of web architectures.

So make use of unit testing tools to do the unit testing before moving to another process in the software life cycle.

Part 2 of this tutorial covers Generating HTML reports with Junit

Categories: Uncategorized Tags:
  1. January 24th, 2014 at 01:18 | #1

    Nice post. I’d been verifying regularly this website and i am prompted! Very useful info particularly the eventual aspect :) My spouse and i manage this sort of information and facts a good deal. I’d been searching for this kind of details for a long time. Thanks a lot and all the best ..

  2. Kavitha
    November 22nd, 2013 at 00:48 | #2

    The tutorial is really good for a beginner to learn.Thanks !!

  3. Ram RV
    November 5th, 2013 at 11:48 | #3

    Thanks Shrikanth, for sharing this. Now, can you please let me know how can I use the result for a detailed report generation.

  4. Shuchita
    October 5th, 2013 at 00:15 | #4

    Good tutorial which covers many aspects of working with JUnit for Java developers. Linking to some other good tutorials on Junit which I found:
    mkyong junit tutorials
    javaexperience junit tutorials
    wikipedia junit page

  5. ashish
    July 3rd, 2013 at 01:26 | #5

    @Shrikant kale thanku very mutch..very usefull…….

  6. ashish
    July 3rd, 2013 at 01:23 | #6

    @Shrikant kale thanku very mutch..very usefull…….

  7. December 30th, 2012 at 13:22 | #7

    another point I would like to mention about junit and eclipse is that different versions of eclipse IDE support different versions of Junit. One needs to verify the compatibility before choosing any particular version of Eclipse IDE.
    JUnit Eclipse Support

  8. December 26th, 2012 at 02:48 | #8

    HI GUYS ,I am Providing you the complete Solution for this : KEEP CODING

    Note : Just Create hierarchy :

    E:.
    │ .classpath
    │ .project
    │ projectSet.psf

    ├───.settings
    │ org.eclipse.jdt.core.prefs

    ├───bin
    │ └───com
    │ └───cxt
    │ └───java
    │ ├───source
    │ │ Bank.class
    │ │
    │ └───test
    │ BankTest.class
    │ BankTestSuite.clas
    │ MyTestRunner.class

    └───src
    └───com
    └───cxt
    └───java
    ├───source
    │ Bank.java

    └───test
    BankTest.java
    BankTestSuite.java
    MyTestRunner.java

    —————————————————————————————

    **STEP 1 : CREATE THE SOURCE PROGRAM.**

    package com.cxt.java.source;

    public class Bank {

    public long accno;
    public double amount;
    public double withdraw;

    static double security_amount=1000.00;

    public double depositeMoney(long accountno, double amount) {
    this.accno=accountno;
    this.amount=amount;
    this.amount+=amount;
    System.out.println(“Amount “+amount+” has been successfully deposited into A/C Number : “+accountno);
    System.out.println(“Available Balence : “+this.amount+” & Security Deposite : “+security_amount);
    return amount;

    }

    public double withdrawMoney(long accountno, double amount) {
    this.accno=accountno;
    this.amount=amount;
    this.amount-=amount;

    if (this.amount= amount) {
    System.out.println(“Withdrawing form the Security Deposite Ammount”);
    this.security_amount-=amount;
    System.out.println(“Amount $ “+amount+” has been successfully withdrawed from A/C Number : “+accountno);
    }
    else
    {
    System.out.println(“The enterd amount is bigger than the available as & security deposited amount.\n Hence Can’t be withdraw.”);
    System.out.println(“Amount $ 00.00 has been successfully withdrawed from A/C Number : “+accountno);
    }

    System.out.println(“Available Balence : “+this.amount+” & Security Deposite : “+security_amount);
    return this.amount;
    }

    public double checkBalence() {

    System.out.println(“Current A/C Balence is :”+this.amount+” in “+this.accno+” A/C number”);

    return this.amount;
    }

    }

    **STEP 2 : CREATE TEST CLASS.**

    package com.cxt.java.test;

    import static org.junit.Assert.assertEquals;

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

    import com.cxt.java.source.Bank;

    public class BankTest {

    static Bank bank;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    if (bank==null) {
    bank=new Bank();
    } else {
    System.out.println(“Bank object should be singleton in nature..”);
    }
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    bank=null;
    System.gc();
    }

    @Before
    public void setUp() throws Exception {
    System.out.println(“setUp()”);
    }

    @After
    public void tearDown() throws Throwable {
    System.out.println(“tearDown()\n”);
    //System.gc();
    }

    @Test
    public final void testDepositeMoney() {
    long accno=1001;
    double amount=1000.00;
    double expected=amount;
    double actual=bank.depositeMoney(accno, amount);
    assertEquals(“Exception raised in testDepositeMoney()”,expected,actual,0.0);
    }

    @Test
    public final void testWithdrawMoney() {
    long accno=1000;
    double amount=1000.00;
    double expected=0.0;
    double actual=bank.withdrawMoney(accno, amount);
    assertEquals(“Exception Raised into testWithdrawMoey()”,expected, actual,0.0);
    }

    @Test
    public final void testWithdrawAccessMoney() {
    long accno=1001;
    double amount=100000.00;
    double expected=0.0;
    double actual=bank.withdrawMoney(accno, amount);
    assertEquals(“Exception Raised into testWithdrawMoey()”,expected, actual,0.0);
    }
    }

    **STEP 3 : CREATE TEST SUITE CLASS**

    package com.cxt.java.test;

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

    import junit.framework.TestResult;
    import junit.framework.TestSuite;

    @RunWith(Suite.class)
    @SuiteClasses({
    BankTest.class
    })
    public class BankTestSuite {

    }

    **STEP 4 : CREATE TEST RUNNER**

    package com.cxt.java.test;

    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;

    public class MyTestRunner {

    public static void main(String[] args) {
    Result result = JUnitCore.runClasses(BankTestSuite.class);
    for (Failure failure : result.getFailures()) {
    System.out.println(failure.toString());
    }
    System.out.println(“Was Successful.?”+result.wasSuccessful());
    System.out.println(“Total Run Count : “+result.getRunCount());
    System.out.println();System.out.println();System.out.println();
    System.out.pritnln(“… Jay Maharastra …”);
    }

    }

  9. Sumesh
    December 24th, 2012 at 03:20 | #9

    This is nice, if anyone interested in going one step beyond this, read http://apitestingwithjunit.blogspot.in/
    It tells how to make full use of junit for functional testing by overcoming the fatal assertions problem.

  10. Shrikant Kale
    December 11th, 2012 at 23:56 | #10

    Please Provide some real-time examples ….

  11. Shrikant Kale
    November 27th, 2012 at 07:19 | #11

    Thanks .. good tutorial but should provide the details about the TestSuites…..

  12. vijay
    September 22nd, 2012 at 04:43 | #12

    wow! nice tutorial..!!

  13. Ajimon
    February 2nd, 2012 at 20:03 | #13

    Thanks , nice tutorial

  14. Priyanka
    January 6th, 2012 at 04:35 | #14

    Thank you very much. This was a great help to me. Please do keep up the good work.

  15. February 3rd, 2011 at 08:06 | #15

    THanks for a very helpful tutorial

  16. March 27th, 2010 at 21:44 | #16

    Good tutorial.

  1. March 26th, 2010 at 22:02 | #1
  2. March 27th, 2010 at 20:55 | #2