Last autumn, I wrote about using JDepend inside JUnit test to verify a project’s package structure during the build process.

While using JDepend, I found several bugs in it and noticed that not all features of newer Java versions are supported. Additionally, I wanted to use also other code analysis tools. This led to a new project: code-assert.

It provides a common Java API for code analysis tools, thought to be used in JUnit tests. It includes the following checks:

  • Verify the package (and class) structure of a project.
  • Find code smells with FindBugs and PMD.
  • Find code duplications with CPD.
  • Set minimum values for the test coverage with JaCoCo.

An example test looks like this:

AnalyzerConfig config = AnalyzerConfig.maven().main();

BugCollector collector = new BugCollector()
    .because("It's checked and OK like this",
        In.classes(Matcher.class, Ruleset.class).ignore("DP_DO_INSIDE_DO_PRIVILEGED"),
        In.locs("FileParser#parse", "*Test", "Rulesets").ignore("URF_UNREAD_FIELD"));

FindBugsResult result = new FindBugsAnalyzer(config, collector).analyze();
assertThat(result, hasNoBugs());

The basic structure is the same for all five tools:

  • AnalyzerConfig defines which classes / source files to be included in the check.
  • Collector defines more precisely how certain parts of the code should be checked. Rules can be given with (because) or without (just) a textual explanation.
  • Analyzer executes the check.
  • The result can be asserted with several JUnit Matchers (e.g. hasNoBugs).

I’m currently using the complete set of checks in a project. If one wants to use it, it’s crucial to do so seriously from the start. Introducing it in an already running project is really hard. Quite some time is needed to define and fine-tune the rules. False positives can and probably will appear during the whole development process. Be prepared for this. It can show new facets of bugs and code structure. I’m not sure how much of the checks really should be used and how much they really help avoiding bugs and improving code quality. But it’s definitely an interesting experiment.

Happy coding.