Putting It All Together
The final
build.xml looks like this (the
cobertura-instrument task, testing targets, and so on are omitted for clarity):
<target name="coverage_check" depends="check_against_previous_rate">
<antcall target="coverage_report"/>
</target>
<target name="coverage_report">
<cobertura-report format="xml" destdir="." />
</target>
<target name="check_against_previous_rate" depends="coverage_xml_to_properties">
<property file="build/coverage.properties" />
<cobertura-check totallinerate="${coverage.line-rate}" />
</target>
<target name="coverage_xml_to_properties">
<xslt in="coverage.xml" out="build/coverage.properties" style="src/xsl/coverage.xsl" />
</target>
Note that a new coverage report is generated only when the coverage check has passed (that is, the coverage rate is as good as or better than the previous successful build).
Remember to bootstrap this approach by executing the coverage_report target before the very first execution of coverage_check. In practice, you should add another cobertura-report task to produce an HTML report too.
Tracking Rate of Improvement
A nice little add-on to the incremental improvement approach is tracking the rate of improvement by logging the coverage rate to a file. You accomplish this by using the Ant echo task:
<target name="time">
<tstamp>
<format property="date.time" pattern="yyyy-MM-dd HH:mm"/>
</tstamp>
</target>
<target name="log" depends="time">
<echo file="${history.txt}" append="true">
${date.time};total.line-rate;${total.line-rate}
</echo>
</target>
Measurable Results, Visible Improvement
A week after implementing this strategy in the project I mentioned in the introduction, we achieved a 30 percent coverage improvement (albeit from a very modest baseline). Most gratifyingly, developers who previously were reluctant to write tests are now taking pride in seeing the project's coverage rates improve.
In the true democratic spirit of agile development, each and every team member can raise the target for the whole project by writing more testsno arbitrary targets, no Colonel Cathcart.
And you don't need to stop there. You can use the incremental improvement strategy for other code metrics too. Because most code-checking tools produce XML-formatted output, you can filter out the relevant metrics using an XSL template and use them as input values for checking in the following build.