开发者

Writing Unittest for generic classes... best approach?

开发者 https://www.devze.com 2022-12-08 18:02 出处:网络
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 a

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 fo开发者_如何学JAVAr each of these types and instead use one testclass for every datatype?

Thanks Patrick


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.


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>.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消