Tuesday, April 08, 2014

Parameterized JUnit Tests by Example


public class ReverseString {

 public static void main(String[] args) {
  String str = "abracadabra0";
  System.out.println(reverseStr(str));
 }

 public static String reverseStr(String str) {
  StringBuilder sb = new StringBuilder();
  for (int i = str.length() - 1; i >= 0; i--) {
   sb.append(str.charAt(i));
  }
  return sb.toString();
 }

}
import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ReverseStringTest {
 String testStr = "";
 String expectedStr = "";
 

 @Rule
 public ExpectedException exception = ExpectedException.none();

 public ReverseStringTest(String ts, String es) {
  this.testStr = ts;
  this.expectedStr = es;
 }
 
 @Parameters
 public static Iterable data() {
  return Arrays
    .asList(new Object[][] { { "abracadabra0", "0arbadacarba" },
      { null, null }, { "", "" } });
 }


 @Test
 public void test() {
  if (testStr == null) {
   exception.expect(NullPointerException.class);
  }
  assertEquals(expectedStr, ReverseString.reverseStr(testStr));
 }

}

No comments: