问题
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
回答1:
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.
回答2:
Your question forces me to give two comments rather than a direct answer:
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 onlystatic
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...
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).
来源:https://stackoverflow.com/questions/46477696/code-coverage-does-not-reach-class-declaration