简体   繁体   中英

Code coverage does not reach class declaration

Is there any way to get the code coverage to cover the class declaration of a class like so?

public class MyClass{

    public static void foo(int bar){
        System.out.println("The Number is: "+bar);
    }
}

I can easily hit the foo method with JUnit testing, but the MyClass declaration stays red. Is this because the class itself has no constructor? And if so, is there any way to cover that bit of code, without changing the code of the class itself?

Thanks

This may depend on your specific environment. But I just checked Eclipse/EclEmma and see the behavior you describe.

Remember, the class does have a constructor - it's the default constructor. If you make a test that simply calls new MyClass() , it looks like the red mark goes away.

BUT - the preferred approach for a class with only static methods is to mark the class as final and create a private constructor. Of course if you create a private constructor, that will show up as red in the code coverage - because you can't call a private constructor!

Finally though, remember that code coverage is a tool. I wouldn't get all worked up about a red mark in the viewer.

Your question forces me to give two comments rather than a direct answer:

  1. Do not use the static key word unless you have a very good reason.

    It is a common misconception that classes used to provide common functionality should have (only) static methods. That comes from the habit to call a class with only static methods an utility classes .

    Such all static utility classes will make your code hard to extend and hard to reuse. And you throw away one of the most powerfull tools in OOP: polymorphism . And your one and only advantage is not needing to write the constructor call...

  2. Looking for CodeCoverage is easy since we have tools giving us numbers for that and managers love to judge developers by numbers they produce...

    But much more important is the requirement coverage . Unfortunately we have no tools to measure requirement coverage . The only tool we have to reach a 100% requirement coverage is test/behavior driven developement (TDD/BDD).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM