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:

Book notes: Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems, by Martin Kleppmann

My notes from the excellent book on how software has evolved to handle data from hierarchical databases to the NoSQL -  https://www.goodrea...