The best code coverage for Scala
Join the DZone community and get the full member experience.Join For Free
the best code coverage metric for scala is
. simple as that. it suits the typical programming style in scala best. scala is a chameleon and it can look like anything you wish, but very often more statements are written on a single line and conditional “
” statements are used rarely. in other words,
metrics are not helpful.
scala runs on jvm and therefore many existing tools for java can be used for scala as well. but for code coverage it’s a mistake to do so.
one wrong option is to use tools that measure coverage looking at bytecode like jacoco . even though it gives you a coverage rate number, jacoco knows nothing about scala and therefore it doesn’t tell you which piece of code you forgot to cover.
another misfortune are tools that natively support line and branch coverage metrics only. cobertura is a standard in java world and xml coverage report that it generates is supported by many tools. some scala code coverage tools decided to use cobertura xml report format because of its popularity. sadly, it doesn’t support statement coverage.
why? because a typical scala statement looks like this (a single line of code):
def f(l: list[int]) = l.filter(_ > 0).filter(_ < 42).takewhile(_ != 3).foreach(println(_))
neither line nor branch coverage works here. when would you consider this single line as being covered by a test? if at least one statement of that line has been called? maybe. or all of them? also maybe.
where is a branch? yes, there are statements that are executed conditionally, but the decision logic is hidden in internal implementation of list. branch coverage tools are helpless, because they don't see this kind of conditional execution.
what we need to know instead is whether individual statements like
_ > 0
_ < 42
have beed executed by an automated test. this is the statement coverage.
scoverage to the rescue!
luckily there is a tool named scoverage . it is a plugin for scala compiler. there is also a plugin for sbt . it does exactly what we need. it generates html report and also own xml report containing detailed information about covered statements.
scoverage plugin for sonarqube
recently i have implemented a plugin for sonar 4 so that statement coverage measurement can become an integral part of your team's continuous integration process and a required quality standard. it allows you to review overall project statement coverage as well as dig deeper into sub-modules, directories and source code files to see uncovered statements.
Published at DZone with permission of Rado Buranský, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.