In July 2012 a until now rarely documented feature was added to GWT (related Git-Commit). It’s code coverage on the client side.
How it works
You can activate it via the System-Property “gwt.coverage”. The property-value must contain either all named Java source files separated by comma, or it must point to a text file containing all Java source files; one per line. Now the GWT compiler will instrument the corresponding JavaScript which is based on the named Java source files. Additionally the compiler registers an onUnLoad-Event, which stores the code coverage into LocalStorage of the browser.
Maven-Example
I have a simple GWT-Project which is build via Maven. In the main source (src/main/java/org/jajax/gwt/test/client/MyEntryPoint.java) I have the following file:
1 2 3 4 5 6 7 8 9 10 11 12 | package org.jajax.gwt.test.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.Window; public class MyEntryPoint implements EntryPoint { @Override public void onModuleLoad() { Window.alert("Hello world"); } } |
Additionally I created a Textfile (target/gwt-coverage-sources.txt) with the following content:
1 | org/jajax/gwt/test/client/MyEntryPoint.java |
Now only the configuration of GWT is missing. You have to add the Parameter gwt.coverage=target/gwt-coverage-sources.txt.
1 2 3 4 5 6 7 8 | <plugin> <groupid>org.codehaus.mojo</groupid> <artifactid>gwt-maven-plugin</artifactid> <version>2.7.0</version> <configuration> <extrajvmargs>-Dgwt.coverage=target/gwt-coverage-sources.txt</extrajvmargs> </configuration> </plugin> |
Now if you run you application, you can access the code coverage via JavaScript
1 | localStorge.getItem("gwt_coverage"); |
You will get a JSON with the following content:
1 | {"org/jajax/gwt/test/client/MyEntryPoint.java":{"6":1,"10":1}} |
The inner object has for every line as key a value of 0 for a missing coverage or 1 for covered code.
Conclusion
This feature is very interesting, because the alternatives are very rare. The old option to use Emma / Jacoco is not functional anymore with the current versions of Java (1.8), GWT (2.7.0 / 2.8.0-SNAPSHOT), etc. So this feature seems to be a good alternative. Unfortunately there is no tool to extract the code coverage of Unit-Tests or Integration-Tests, but I will release a Tool, which connects the GWT code coverage with Jacoco Reports. So stay tuned!