Monday, January 10, 2011

JUnit Annotation Type - RunWith

7. Annotation Type RunWith:  

When a class is annotated with @RunWith to extends a class annotated with @RunWith, JUnit will invoke the class it references to run the tests in the class instead of the runner built into JUnit. For example, suites in the JUnit 4 are built using RunWith, and a custom runner names Suite:

@RunWith(Suite.class)
@SuiteClasses(ATest.class, BTest.class, CTest.class)
public class ABCSuite{
}

Class Parametrized:

The custom runner Parameterized implements parameterized tests. When running a parameterized test class, instances are created for the class-product of the test methods and test data elements.

Junit Parameterized Test is new feature invoked in JUnit4, it means vary parameter value for unit test. In fact some method have many difference parameters value to input, if you write a testcase for per parameter value, this could be quite large numbers of test case you need to code in Junit, which has supported class Parameterized as for Parameterized Test function, use @RunWith annotate Parameterized as this test class runner, use @Parameters annotate method data() and it have to return List[], the parameter will pass into class constructor as argument.

Example:

Write the following JUnitTest in Eclipse.

import java.util.Arrays;
import java.unit.Collection;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

 @RunWith(value = Parameterized.class)
public class JUnitTest extends Assert{

            String name;
            int age;

            public JUnit4Test(String name, int age){
                      this.name = name;
                      this.age = age;
            }

           @Parameters
           public static Collection<Object[]> data(){
                    object[][] data = new Object[]{{"Parameterized test1",       10},{"Parameterized test2", 20}};
                    return Arrays.asList(data);
           }

          @Test
          public void testOut(){
                   System.out.println(name + " " + age);
          }

Output:
Parameterized test1 10
Parameterized test2 20

No comments:

Post a Comment