JUnit 4 Tutorial 5 – Suite Test

The “Suite Test” means bundle a few unit test cases and run it together. In Junit, both @RunWith and @Suite annotation are used to run the suite test.

The below example means both unit test JunitTest1 and JunitTest2 will run together after JunitTest5 is executed.

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
 
/**
 * JUnit Suite Test
 * @author mkyong
 *
 */
 
@RunWith(Suite.class)
@Suite.SuiteClasses({
        JunitTest1.class,
        JunitTest2.class
})
public class JunitTest5 {
}

Result

@BeforeClass - oneTimeSetUp
@Before - setUp
@Test - testEmptyCollection
@After - tearDown
@Before - setUp
@Test - testOneItemCollection
@After - tearDown
@AfterClass - oneTimeTearDown

P.S Result is from JunitTest1 and JunitTest2 unit test

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: ionizer loans()

  • Pingback: extra resources()

  • Pingback: house blue()

  • Pingback: pay day loans()

  • Pingback: shark plumbing fittings()

  • Pingback: plumber 33179()

  • Pingback: locksmiths kaiserslautern()

  • Pingback: c & e locksmiths brandon()

  • Pingback: electrician trade schools in nj()

  • Pingback: electrician v the world()

  • Pingback: water ionizer loans()

  • Pingback: paypal loans()

  • Pingback: parking()

  • Pingback: alkaline water machine()

  • Pingback: laan penge billigt()

  • Pingback: laan penge online()

  • Pingback: mobile porn movies()

  • Pingback: parking()

  • Pingback: tvpackages.net()

  • Pingback: DIRECTV vs Cable()

  • Pingback: kangen()

  • Pingback: kangen()

  • Pingback: alkaline water()

  • Pingback: water ionizer()

  • Pingback: watch movies online()

  • Pingback: watch free movies online()

  • Pingback: watch movies online()

  • Pingback: Blue Coaster33()

  • olive

    hi
    i have few doubts, could you please clarify
    in Step3 : Create Test Suite Class : – how can i get the details of junit test classes executed( pass/fail, test case execution start time, end time etc..) from this suite class ?
    in Step4 : Create Test Runner : How Can i call/execute this class from Ant Build File or Jenkins server ?
    I am trying to generate a custom html report file for the Junit Test Suite, so for that i want to know above details.

  • YourBestFriend

    Oh no!!! Where is your eyes friend????!!!

  • Shishupal Singh

    realyy nice explaination of JUNIT test with example

  • http://about.me/shrikant_kale Shrikant kale

    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 ...");
    	  }
     
     
     
     
    }
  • rajasekhar burepalli

    Hi MK Yong …

    Iam big fan of you. Recently i started reading your posted on various technologies, it is really help for others.
    I have a doubt on JUNIT Testcases. Please provide the information to that
    public class Emp
    {
    public void insertEmp(Connection,String sql)
    {
    // Logic to perform conn and insert an employee object into the database
    }
    }
    So, i want to perform a testcase to the above Emp class insertEmp(-,-), but the return type of insertEmp(-,-) is void . so How should we need to write testcase for that insert(-,-)
    ASP please give the solution..
    Thank you…………

  • Shrikant Kale
     
    PLEASE HELP TO SOLVE THE ISSUE.
     
    ============================================
     
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package junit1;
     
    /**
     *
     * @author Shrikant.Kale
     */
    public class JUNIT1 {
     
       public int add(int x, int y) {
           return x+y;
       }
     
       public int sub(int x, int y) {
           return x-y;
       }
     
       public int mult(int x, int y) {
           return x*y;
       }
     
    }
    ------------------------------------------------
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package junit1;
     
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import static org.junit.Assert.*;
     
    /**
     *
     * @author Shrikant.Kale
     */
    public class JUNIT1Test {
     
        JUNIT1 test1;
     
     
        @Before
        public void setUp() {
            System.out.println("startUp()");
            test1=new JUNIT1();
        }
     
        @After
        public void tearDown() {
            System.out.println("tearDown()");
            System.out.println();
            test1=null;
        }
     
        @Test
        public void testAdd() {
            System.out.println("Testing add()");
     
            assertEquals(10,test1.add(5, 5)); 
     
        }
     
        /**
         * Test of sub method, of class JUNIT1.
         */
        @Test
        public void testSub() {
            System.out.println("Testing sub()");
     
            assertEquals(10,test1.sub(20,10));
     
        }
     
        /**
         * Test of mult method, of class JUNIT1.
         */
        @Test
        public void testMult() {
            System.out.println("Testing mult()");
     
            assertEquals(100,test1.mult(10,10));
     
        }
    }
     
     
    ----------------------------------------------
     
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package junit1;
     
    import junit.framework.TestResult;
    import junit.framework.TestSuite;
     
    /**
     *
     * @author Shrikant.Kale
     */
     
     
    public class JUnitTestSUITE {
     
        public static void main(String[] args) {
     
            TestSuite suite= new TestSuite(JUNIT1Test.class);
     
            TestResult result=new TestResult();
     
            suite.run(result);
     
            System.out.println("Total Run Test : "+result.runCount());
     
            System.out.println("Was Successful : "+result.wasSuccessful());
     
        }
     
    } 
     
    ============================================
     
    run:
    Total Run Test : 1
    Was Successful : false
    BUILD SUCCESSFUL (total time: 0 seconds)
     
    ........................................................................
  • http://abhinandanmk.blogspot.com kulkar

    does the @RunWith(Suite.class) always run the classes in @Suite.SuiteClasses() in the order they are specified?

  • Monika

    Hi. Is there any way to use a class object initialized in first Test method to be used in all other Test methods in the same class. Like

    public class TestCl extends TestCase
    {
    Student stud;
    Fees fee;
    @Test
    public void create()
    {
    fee=new Fee();
    fee.setAmt(10);
    feeService.save(fee);
      stud=new Student();
      stud.setName("Monika");
     stud.setFees(fee);
      studService.save(stud);
    }
    @Test
    public void testFeeByStud()
    {
    Fee feeFound= studService.findFeeByStud(stud);
    //Here stud is always null. Can we get the stud initializes in previous method.
    Assert.assertNotNull(feeFound);
    }
    }
    
    • kapil

      use setup();

  • Manoj

    Thanks for your all example and support. It was really helpful to understand in quick time.

  • Pingback: Integrando Testes de JUnit ao Projeto « Como Fiz()

  • http://testing-associates.com rastogi

    Nice article, depicting the topics effectively.

    keep up the work.

    rastogi

    Consultants available for Software testing, Test Management requirements. reach us at Testing-Associates

  • Pingback: JUnit Tutorials | Tutorials()