Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

java - JUnit: testing helper class with only static methods

I am testing a helper class with only static methods with JUnit4 and Cobertura. Testing methods was easy task and is done already.

However, cobertura shows that the class is not covered by tests completely, as it is not instantiated anywhere.

I don't want to create an instance of this class (it is a helper class), so first solution is to hide constructor (which is generally good approach for helper class).

Then cobertura complains that the empty private constructor is not covered by tests.

Is there any solution to achieve 100% code coverage for such situation?

Code coverage is required from top level management (in this case), so for me obtaining 100% for this particular class is quite helpful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are several solutions:

  1. You can add a public constructor and call it from a test. While it doesn't make sense, it also doesn't hurt (much).

  2. Create a dummy static instance (you can call the private constructor here). Ugly but you can give the field a name to communicate your intent (JUST_TO_SILENCE_COBERTURA is a good name).

  3. You can let your test extend the helper class. That will intrinsically call the default constructor but your helper class can't be final anymore.

I suggest the last approach especially because the class can't be final anymore. If a consumer of your code wants to add another helper method, they can now extend the existing class and receive one handle to get to all helper methods. This creates a coupling of the helper methods which communicates the intent (these belong together) - which is impossible if the helper class is final

If you want to prevent users to accidentally instantiate the helper class, make it abstract instead of using a hidden constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...