D. Ace D. Ace - 3 months ago 30
Java Question

how to use parametized Junit tests for this string reverse code

I read somewhere that I can use @RunWith(JUnitParamsRunner.class) but I have no idea how to use it to test my string reverse method:

Here's my class:

public class StringReverse {

public static String reverse(String s){
List<String> tempArray = new ArrayList<String>(s.length());
for(int i = 0; i <s.length(); i++){
tempArray.add(s.substring(i, i+1));
}
StringBuilder reverseString = new StringBuilder(s.length());
for(int i = tempArray.size() - 1; i >=0; i--){
reverseString.append(tempArray.get(i));
}
return reverseString.toString();
}

}


Here's my test class:

public class StringReverTest {

@Test
public void test() {
StringReverse s = new StringReverse();
assertEquals("cba", s.reverse("abc"));
assertEquals("", s.reverse(""));
assertNotEquals("abc", s.reverse("abc"));

}
@Test(expected = NullPointerException.class)
public void testThrowNPE(){
StringReverse s = new StringReverse();
s.reverse(null);
throw new NullPointerException();
}

}


Please can someone show how exactly do I test the above using parametized test?

Thanks

Answer

You could replace your first test with this one:

@Test
@Parameters(method = "reverseValues")
public void reverseString(String input, String output) {
    StringReverse s = new StringReverse();
    assertEquals(output, s.reverse(input));
}

private Object[] reverseValues() {
     return new Object[]{
             new Object[]{"abc", "cba"},
             new Object[]{"", ""}
        };
}

The second test doesn't need the throw new NullPointerException() line:

@Test(expected = NullPointerException.class)
public void testThrowNPE(){
    StringReverse s = new StringReverse();
    s.reverse(null);
}

The expected annotation will verify that s.reverse(null) throws a NullPointerException.