Junit Test Suite

Test Suite means combined multiple test cases . when I run test suite all test case associated with suite will execute. In Junit we will create test suite with two ways Test Runner class or using annotation  @RnWith and @Suite, here is a example for both type. I have created two Junit test case “JunitTest1.java” and “JunitTest2.java”

package com.test;

import org.junit.*;

public class JunitTest1 {

    @BeforeClass
    public static void beforeClassAnnotation() {        
      System.out.println("@BeforeClass - for junit class 1");
    }

    @AfterClass
    public static void afterClassAnnotation() {       
      System.out.println("@AfterClass - for junit class 1");
    }  

    @Test
    public void testAnnotation() {       
        System.out.println("@Test - first class test method");
    }    
}




package com.test;

import org.junit.*;

public class JunitTest2 {

    @BeforeClass
    public static void beforeClassAnnotation() {        
      System.out.println("@BeforeClass - for junit class 2");
    }

    @AfterClass
    public static void afterClassAnnotation() {       
      System.out.println("@AfterClass - for junit class 2");
    }  

    @Test
    public void testMethod2() {       
        System.out.println("@Test - Second class test method");
    }    
}

Test Suite using @RunWith and @Suite annotation.


package com.test;

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

@RunWith(Suite.class)
@Suite.SuiteClasses({
      JunitTest1.class ,JunitTest2.class
})
public class JunitTestSuite {
}


Run above suite file using Junit Test you will see as below log is generated.

@BeforeClass - for junit class 1
@Test - first class test method
@AfterClass - for junit class 1
@BeforeClass - for junit class 2
@Test - Second class test method
@AfterClass - for junit class 2


Test suite using Test runner  class.


package com.test;

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

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(JunitTest1.class);      
      result = JUnitCore.runClasses(JunitTest2.class);    
   }
}


Run above suite file using java console you will see as  below log is generated.


@BeforeClass - for junit class 1
@Test - first class test method
@AfterClass - for junit class 1
@BeforeClass - for junit class 2
@Test - Second class test method
@AfterClass - for junit class 2


Leave comment if you have any query.

No comments:

Post a Comment

Leave your comments, queries, suggestion I will try to provide solution