-2

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

D. Ace
  • 398
  • 4
  • 9
  • 25

1 Answers1

3

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.

Julieta
  • 407
  • 2
  • 8
  • thanks @Julieta is this what they mean by parametised test? Basically the method takes in some parameters? – D. Ace Aug 28 '16 at 21:44
  • Yes, is that what they mean. You create a list of parameters and iterate among them. This is useful when you want to test the same code under different conditions :) – Julieta Aug 28 '16 at 21:51