views:

62

answers:

3

Hello! I'm supposed to write unit tests for a project whose code another colleague has written. He created a generic list class. Now i'm thinking about, the best way to create the unittests for the class and how to avoid much repetitive code. The List class can be instaniated with String, Integer and some other Types. How can i avoid to write a testclass for each of these types and instead use one testclass for every datatype?

Thanks Patrick

+3  A: 

Does the class you're testing treat its contained elements in any special way based on their type? If it treats instances of String and Integer the same, then you can simply test it once with String and assume that Integer will work just fine.

Unit testing depends heavily on the expected behavior.

Max A.
A: 

JUnit4 has a parametrized runner which will let you write one test for all the different types. This assumes that there is no substantial behavior difference between the different types, so the test can exercise the class the same way.

That being said, I have to echo the comments that the underlying circumstances of the question is very bizarre. The JDK has plenty of list implementations and it is very strange to be writing a class for this purpose.

Yishai
The List has some functionality to undo changes. He needed that for the project. Why do i write the tests for it? My colleagues never have worked with it (they despise such witchcraft ;-)) and i (new guy in the company) have researched to topic a little bit more. So my Boss has told me to support my colleague in his project by writing the unittests. It's also supposed to show them the benefits of using a framework like Junit.
Patrick
+1  A: 

I agree with Max A. that you need to test the expected behavior. If the generic class behaves differently for different parameterized types, then you need to test that. Otherwise, testing with one type should be adequate.

Also, if you want to assert that the generic class can be instantiated for any type, you may want to write a test that instantiates the class for Object. This would be a somewhat odd test in that if it compiles it "passes", but if you keep your tests as a regression of the systems expected behavior (and you should) then this test will guard against someone changing the generic class to be parameterized with <T extends YYY>.

Thanks for the usefull hint! :-)
Patrick