1

Could you help me? I have the object with 50 fields (String a, Integer b ...) and I have the method with 'if' statement like this:

if( a==null OR b==null OR ...(for any field ) ) {
throw My Exception();
}

I am writing unit test for this method. I created 50 instantiations of my object like this

 1. a=null, <-- only a is null for this instantiation 
 2. b=null <--- only b is null for this instantiation
      .
      .
      .
 50. n=null <--- only n is null for this instantiation

My question is, do I have to write 50 @Test methods for this?

I wrote one @Test method like this but I am not sure that this is correct according to the paradigm of unit tests.

@Test
public void test(){    
   for(int a=0;a<50;a++){    
     try{    
        //I call the method with my if statament for any of 50 object
        }
       catch(MyException e){
        y++;
       }
    }    
 Assert.assert(y,50);    
}
user3740179
  • 133
  • 10

2 Answers2

1

I'm writing an answer using a JUnit 4 parameterized test. Since you already created 100 different instances of your object, just put that code in the parameters method.

@RunWith(Parameterized.class)
public class MyParameterizedTest {

    MyObject value;

    public MyParameterizedTest(MyObject value) {
        this.value = value;
    }

    @Parameterized.Parameters
    public static List<MyObject> parameters() {
        // create a list with 100 different instances of your object...
        // return it...
    }

    @Test(expected = MyException.class)
    public void testMethodCallShouldThrowException() throws MyException {
        // I call the method with my if statament for any of 100 object
        myMethod(value);
    }
}

Link to docs: Parameterized

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
1

This is probably not the answer you like to hear, but the precondition for meaningful unit tests is a reasonable design. Having a class with 100 attributes is definitely a design that can be improved.

So think about redesigning your class first.

Edit: At first sight my statement seems to contradict the Test Driven Design approach where you implement the unit tests without having implemented the classes. But as a result this will probably prevent you from ending up with a 100 field class. So it is not a contradiction.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45