Junit Time and Parameterized Test

One: Junit Time test

The “Junit Time Test” means if an unit test takes longer than the specified number of milliseconds to run, the test will be terminated and marked as failed. This is an extremely useful case to test these time-consuming operations, for instance: you connect a database to retrieve items, if it has no return after taking longer than one minute, you probably want to terminate this testcase and mark it as failed.

@Test(timeout = 1000L)
public void searchPersonByName(){
  Person person = dao.search("John");
  assertEquals(person.getName(), "John");
}

In above example, if the time spending on method searchPersonByName is longer than 1000 milliseconds, the Junit engine throws an exception and mark it as failed one, and output the following:

java.lang.Exception: test timed out after 1000 milliseconds

If it is finished within 1000 milliseconds, the testcase passes.

Two: Junit Parameterized Test

Junit Parameterized Test is a new feature invoked in Junit4,  it allows vary parameters value for unit test. In fact some methods have many difference parameters value to input, if you write a testcase for per parameter value, this could be quite large numbers of testcase 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.

Junit4Test.java
@RunWith(value = Parameterized.class)
public class Junit4Test 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

It has many limitations here; you have to follow the JUnit way to declare the parameter, and the parameter has to pass into constructor in order to initialize the class member as parameter value for testing. The return type of parameter class is “List []”, data type has been limited to String or primitive value.

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *

*

code