4

I need to test a method, eg:

public ObjRet foo(string input)
{
...
return objRet;
}

For the above method, one test case involves input = {null, " ", "", etc} which would return the same default object and there are other test cases

Do I need to have separate test cases for each input (even though I need to validate for same default object)

or can i do something like this,

@Test
void testing()
{
  String[] inputs = {null, "", " "};
  List<ObjRet> received = new List<ObjRet>();
  for(string input : inputs)
     received.add(foo(input));

  for(ObjRet obj : received)
      Assert.assertEquals(obj, default);
}

I just want to make sure that if its a good practice to use for loops for assertions

user1810502
  • 531
  • 2
  • 7
  • 19

1 Answers1

3

The JUnitParams library is the perfect way to create the type of parameterized test you're describing. I include it by default with every project because this pattern is so common. See http://code.google.com/p/junitparams/ for the complete documentation (it's so easy it all fits on one page).

With JUnitParams, each String included in the String[] passed to the @Parameters annotation is parsed as a CSV and is split on commas, then leading and trailing whitespace is removed from each token. The number of tokens must also match the number of arguments to the test method. Since you need to include a null, an empty string and a string that consists only of whitespace, you'll need to use a method to provide your parameters as follows:

  private static final Object DEFAULT_VALUE = new String("It works!");
  private static final Object OTHER_VALUE = new String("It's broken!");

  private Object foo(String input) {
    Object output = DEFAULT_VALUE;
    if(input != null && !"".equals(input.trim())) {
      output = OTHER_VALUE;
    }
    return output;
  }

  @SuppressWarnings("unused")
  private Object[] parameters() {
    return $(
          new Object[] { null },
          new Object[] { "" },
          new Object[] { " " }
          // ,"Other value"
        );
  }

  @Test
  @Parameters(method = "parameters")
  public void testing(String input) {
    Object obj = foo(input);
    assertEquals(obj, DEFAULT_VALUE);
  }

The three tests defined in your original question will pass with this example code, but if you uncomment the fourth value ("Other value"), then fourth test will (properly) fail.

Steve Moyer
  • 5,663
  • 1
  • 24
  • 34
  • I am trying to use something like, @Parameters({null, "", " "}) but errors out for null and when I remove null, it throws illegalArg exception saying it "cannot parse the parameters, did u , as separator". Can't we use null, empty string and whitespace in @Param, is there an alternative – user1810502 Dec 05 '13 at 03:42
  • I've updated my answer above with some code to get you started. I've also included a link to the corresponding issue at the JUnitParams project (http://code.google.com/p/junitparams/issues/detail?id=51). – Steve Moyer Dec 05 '13 at 14:59