pmd/pmd_userdocs_extending_testing.html
Travis CI (pmd-bot) d9448f1738 Update documentation
TRAVIS_JOB_NUMBER=3049.2
TRAVIS_COMMIT_RANGE=2fecd9e1efb4...331e29e03439
2018-11-11 23:09:19 +00:00

1605 lines
54 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Learn how to use PMD's simple test framework for unit testing rules.">
<meta name="keywords" content="extendinguserdocs, ">
<title>Testing your rules | PMD Source Code Analyzer</title>
<link rel="stylesheet" href="css/syntax.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!--<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">-->
<link rel="stylesheet" href="css/modern-business.css">
<link rel="stylesheet" href="css/lavish-bootstrap.css">
<link rel="stylesheet" href="css/customstyles.css">
<link rel="stylesheet" href="css/theme-blue.css">
<link rel="stylesheet" href="css/pmd-customstyles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script src="js/jquery.navgoco.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/2.0.0/anchor.min.js"></script>
<script src="js/toc.js"></script>
<script src="js/customscripts.js"></script>
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
<link rel="icon" href="images/favicon.ico" type="image/x-icon">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" title="" href="https://pmd.github.io/pmd/feed.xml">
<script>
$(document).ready(function() {
// Initialize navgoco with default options
$("#mysidebar").navgoco({
caretHtml: '',
accordion: true,
openClass: 'active', // open
save: false, // leave false or nav highlighting doesn't work right
cookie: {
name: 'navgoco',
expires: false,
path: '/'
},
slide: {
duration: 400,
easing: 'swing'
}
});
$("#collapseAll").click(function(e) {
e.preventDefault();
$("#mysidebar").navgoco('toggle', false);
});
$("#expandAll").click(function(e) {
e.preventDefault();
$("#mysidebar").navgoco('toggle', true);
});
});
</script>
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
<script>
$(document).ready(function() {
$("#tg-sb-link").click(function() {
$("#tg-sb-sidebar").toggle();
$("#tg-sb-content").toggleClass('col-md-9');
$("#tg-sb-content").toggleClass('col-md-12');
$("#tg-sb-icon").toggleClass('fa-toggle-on');
$("#tg-sb-icon").toggleClass('fa-toggle-off');
});
});
</script>
</head>
<body>
<!-- Content is offset by the height of the topnav bar. -->
<!-- There's already a padding-top rule in modern-business.css, but it apparently doesn't work on Firefox 60 and Chrome 67 -->
<div id="topbar-content-offset">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container topnavlinks">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="fa fa-home fa-lg navbar-brand" href="index.html">&nbsp;<span class="projectTitle"> PMD Source Code Analyzer Project</span></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<!-- toggle sidebar button -->
<li><a id="tg-sb-link" href="#"><i id="tg-sb-icon" class="fa fa-toggle-on"></i> Nav</a></li>
<!-- entries without drop-downs appear here -->
<li><a href="https://github.com/pmd/pmd/releases/latest" target="_blank">Download</a></li>
<li><a href="https://github.com/pmd/pmd" target="_blank">Fork us on github</a></li>
<!-- entries with drop-downs appear here -->
<!-- conditional logic to control which topnav appears for the audience defined in the configuration file.-->
<!--comment out this block if you want to hide search-->
<li>
<!--start search-->
<div id="search-demo-container">
<input type="text" id="search-input" placeholder="search...">
<ul id="results-container"></ul>
</div>
<script src="js/jekyll-search.js" type="text/javascript"></script>
<script type="text/javascript">
SimpleJekyllSearch.init({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('results-container'),
dataSource: 'search.json',
searchResultTemplate: '<li><a href="{url}" title="Testing your rules">{title}</a></li>',
noResultsText: 'No results found.',
limit: 10,
fuzzy: true,
})
</script>
<!--end search-->
</li>
</ul>
</div>
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<div class="col-lg-12">&nbsp;</div>
<!-- Content Row -->
<div class="row">
<!-- Sidebar Column -->
<div class="col-md-3" id="tg-sb-sidebar">
<ul id="mysidebar" class="nav">
<li class="sidebarTitle">PMD 6.10.0</li>
<li>
<a href="#">About</a>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="pmd_release_notes.html">Release notes</a></li>
<li><a href="pmd_about_help.html">Getting help</a></li>
</ul>
</li>
<li>
<a href="#">User Documentation</a>
<ul>
<li><a href="pmd_userdocs_installation.html">Installation and basic CLI usage</a></li>
<li><a href="pmd_userdocs_making_rulesets.html">Making rulesets</a></li>
<li><a href="pmd_userdocs_configuring_rules.html">Configuring rules</a></li>
<li><a href="pmd_userdocs_best_practices.html">Best practices</a></li>
<li><a href="pmd_userdocs_suppressing_warnings.html">Suppressing warnings</a></li>
<li><a href="pmd_userdocs_incremental_analysis.html">Incremental analysis</a></li>
<li><a href="pmd_userdocs_cli_reference.html">PMD CLI reference</a></li>
<li class="subfolders">
<a href="#">Extending PMD</a>
<ul>
<li><a href="pmd_userdocs_extending_writing_pmd_rules.html">Writing a rule</a></li>
<li><a href="pmd_userdocs_extending_writing_xpath_rules.html">Writing XPath rules</a></li>
<li><a href="pmd_userdocs_extending_defining_properties.html">Defining rule properties</a></li>
<li><a href="pmd_userdocs_extending_metrics_howto.html">Using and defining code metrics</a></li>
<li><a href="pmd_userdocs_extending_rule_guidelines.html">Rule guidelines</a></li>
<li class="active"><a href="pmd_userdocs_extending_testing.html">Testing your rules</a></li>
</ul>
</li>
<li><a href="pmd_userdocs_cpd.html">Copy-paste detection</a></li>
<li class="subfolders">
<a href="#">Tools / Integrations</a>
<ul>
<li><a href="pmd_userdocs_tools_maven.html">Maven PMD plugin</a></li>
<li><a href="pmd_userdocs_tools_ant.html">Ant</a></li>
<li><a href="pmd_userdocs_tools_ci.html">CI integrations</a></li>
<li><a href="pmd_userdocs_tools.html">Other Tools / Integrations</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#">Rule Reference</a>
<ul>
<li class="subfolders">
<a href="#">Apex Rules</a>
<ul>
<li><a href="pmd_rules_apex.html">Index</a></li>
<li><a href="pmd_rules_apex_bestpractices.html">Best Practices</a></li>
<li><a href="pmd_rules_apex_codestyle.html">Code Style</a></li>
<li><a href="pmd_rules_apex_design.html">Design</a></li>
<li><a href="pmd_rules_apex_errorprone.html">Error Prone</a></li>
<li><a href="pmd_rules_apex_performance.html">Performance</a></li>
<li><a href="pmd_rules_apex_security.html">Security</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Ecmascript Rules</a>
<ul>
<li><a href="pmd_rules_ecmascript.html">Index</a></li>
<li><a href="pmd_rules_ecmascript_bestpractices.html">Best Practices</a></li>
<li><a href="pmd_rules_ecmascript_codestyle.html">Code Style</a></li>
<li><a href="pmd_rules_ecmascript_errorprone.html">Error Prone</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Java Rules</a>
<ul>
<li><a href="pmd_rules_java.html">Index</a></li>
<li><a href="pmd_rules_java_bestpractices.html">Best Practices</a></li>
<li><a href="pmd_rules_java_codestyle.html">Code Style</a></li>
<li><a href="pmd_rules_java_design.html">Design</a></li>
<li><a href="pmd_rules_java_documentation.html">Documentation</a></li>
<li><a href="pmd_rules_java_errorprone.html">Error Prone</a></li>
<li><a href="pmd_rules_java_multithreading.html">Multithreading</a></li>
<li><a href="pmd_rules_java_performance.html">Performance</a></li>
<li><a href="pmd_rules_java_security.html">Security</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Java Server Pages Rules</a>
<ul>
<li><a href="pmd_rules_jsp.html">Index</a></li>
<li><a href="pmd_rules_jsp_bestpractices.html">Best Practices</a></li>
<li><a href="pmd_rules_jsp_codestyle.html">Code Style</a></li>
<li><a href="pmd_rules_jsp_design.html">Design</a></li>
<li><a href="pmd_rules_jsp_errorprone.html">Error Prone</a></li>
<li><a href="pmd_rules_jsp_security.html">Security</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Maven POM Rules</a>
<ul>
<li><a href="pmd_rules_pom.html">Index</a></li>
<li><a href="pmd_rules_pom_errorprone.html">Error Prone</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">PLSQL Rules</a>
<ul>
<li><a href="pmd_rules_plsql.html">Index</a></li>
<li><a href="pmd_rules_plsql_bestpractices.html">Best Practices</a></li>
<li><a href="pmd_rules_plsql_codestyle.html">Code Style</a></li>
<li><a href="pmd_rules_plsql_design.html">Design</a></li>
<li><a href="pmd_rules_plsql_errorprone.html">Error Prone</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Salesforce VisualForce Rules</a>
<ul>
<li><a href="pmd_rules_vf.html">Index</a></li>
<li><a href="pmd_rules_vf_security.html">Security</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">VM Rules</a>
<ul>
<li><a href="pmd_rules_vm.html">Index</a></li>
<li><a href="pmd_rules_vm_bestpractices.html">Best Practices</a></li>
<li><a href="pmd_rules_vm_design.html">Design</a></li>
<li><a href="pmd_rules_vm_errorprone.html">Error Prone</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">XML Rules</a>
<ul>
<li><a href="pmd_rules_xml.html">Index</a></li>
<li><a href="pmd_rules_xml_errorprone.html">Error Prone</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">XSL Rules</a>
<ul>
<li><a href="pmd_rules_xsl.html">Index</a></li>
<li><a href="pmd_rules_xsl_codestyle.html">Code Style</a></li>
<li><a href="pmd_rules_xsl_performance.html">Performance</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#">Language Specific Documentation</a>
<ul>
<li><a href="pmd_languages_jsp.html">JSP Support</a></li>
<li><a href="pmd_java_metrics_index.html">Java code metrics</a></li>
<li><a href="pmd_apex_metrics_index.html">Apex code metrics</a></li>
</ul>
</li>
<li>
<a href="#">Developer Documentation</a>
<ul>
<li><a href="pmd_devdocs_development.html">Developer resources</a></li>
<li><a href="pmd_devdocs_building.html">Building PMD from source</a></li>
<li><a href="https://github.com/pmd/pmd/blob/master/CONTRIBUTING.md" target="_blank">Contributing</a></li>
<li><a href="pmd_devdocs_writing_documentation.html">Writing documentation</a></li>
<li><a href="pmd_devdocs_roadmap.html">Roadmap</a></li>
<li><a href="pmd_devdocs_how_pmd_works.html">How PMD works</a></li>
<li><a href="pmd_devdocs_pmdtester.html">Pmdtester</a></li>
<li class="subfolders">
<a href="#">Major contributions</a>
<ul>
<li><a href="pmd_devdocs_major_adding_new_language.html">Adding a new language</a></li>
<li><a href="pmd_devdocs_major_adding_new_cpd_language.html">Adding a new CPD language</a></li>
<li><a href="pmd_devdocs_major_adding_new_metrics_framework.html">Adding metrics support to a language</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#">Project documentation</a>
<ul>
<li class="subfolders">
<a href="#">Trivia about PMD</a>
<ul>
<li><a href="pmd_projectdocs_trivia_news.html">PMD in the press</a></li>
<li><a href="pmd_projectdocs_trivia_products.html">Products & books related to PMD</a></li>
<li><a href="pmd_projectdocs_trivia_similarprojects.html">Similar projects</a></li>
<li><a href="pmd_projectdocs_trivia_meaning.html">What does 'PMD' mean?</a></li>
</ul>
</li>
<li><a href="pmd_projectdocs_faq.html">FAQ</a></li>
<li><a href="license.html">License</a></li>
<li><a href="pmd_projectdocs_credits.html">Credits</a></li>
<li><a href="pmd_release_notes_old.html">Old release notes</a></li>
<li class="subfolders">
<a href="#">Project management</a>
<ul>
<li><a href="pmd_projectdocs_committers_releasing.html">Release process</a></li>
<li><a href="pmd_projectdocs_committers_merging_pull_requests.html">Merging pull requests</a></li>
</ul>
</li>
</ul>
</li>
<!-- if you aren't using the accordion, uncomment this block:
<p class="external">
<a href="#" id="collapseAll">Collapse All</a> | <a href="#" id="expandAll">Expand All</a>
</p>
-->
</ul>
<!-- this highlights the active parent class in the navgoco sidebar. this is critical so that the parent expands when you're viewing a page. This must appear below the sidebar code above. Otherwise, if placed inside customscripts.js, the script runs before the sidebar code runs and the class never gets inserted.-->
<script>$("li.active").parents('li').toggleClass("active");</script>
</div>
<!-- Content Column -->
<div class="col-md-9" id="tg-sb-content">
<div class="post-header">
<h1 class="post-title-main">Testing your rules</h1>
</div>
<div class="post-content">
<div class="summary">Learn how to use PMD's simple test framework for unit testing rules.</div>
<!-- this handles the automatic toc. use ## for subheads to auto-generate the on-page minitoc. if you use html tags, you must supply an ID for the heading element in order for it to appear in the minitoc. -->
<script>
$( document ).ready(function() {
// Handler for .ready() called.
$('#toc').toc({ minimumHeaders: 0, listType: 'ul', showSpeed: 0, headers: 'h2,h3,h4' });
});
</script>
<div id="toc"></div>
<a target="_blank" href="https://github.com/pmd/pmd/blob/master/docs/pages/pmd/userdocs/extending/testing.md" class="btn btn-default githubEditButton" role="button"><i class="fa fa-github fa-lg"></i> Edit me</a>
<h2 id="introduction">Introduction</h2>
<p>Good rules have tests. At least a positive test case - a code example, that triggers the rule and reports
a violation - and a negative test case - a code example, that doesnt trigger the rule - should be created.
Of course, the more tests, the better the rule is verified. If the rule is more complex or defines properties,
with which the behavior can be modified, then these different cases can also be tested.</p>
<p>And if there is a bug fix for a rule, be it a false positive or a false negative case, it should be accompanied
with an additional test case, so that the bug is not accidentally reintroduced later on.</p>
<h2 id="how-it-works">How it works</h2>
<p>PMDs built-in rules are organized in rulesets, where all rules belonging to the same category are placed
in a single ruleset, such as “category/java/bestpractices.xml”.
Each category-ruleset has a single abstract base test class, from which the individual test classes inherit.
We have one test class per rule, which executes all test cases for a single rule. The actual test cases are
stored in separate XML files, for each rule a separate file is used.</p>
<p>All the test classes inherit from <code class="highlighter-rouge">net.sourceforge.pmd.testframework.PmdRuleTst</code>,
which provides the seamless integration with JUnit. This base class determines the language, the category name
and the rule name from the concrete test class. It then searches the test code on its own.
E.g. the individual rule test class
<code class="highlighter-rouge">net.sourceforge.pmd.lang.java.rule.bestpractices.AbstractClassWithoutAbstractMethodTest</code> tests the
rule with the name “AbstractClassWithoutAbstractMethod”, which is in the category “bestpractices” for the
language “java”.</p>
<p>The test code (see below <a href="#test-xml-reference">Test XML Reference</a>) describes the test case completely with
the expected behavior like number of expected rule violations, where the violations are expected, and so on.</p>
<p>When you are running the test class in your IDE (e.g. Eclipse or IntelliJ IDEA) you can also select a single
test case and just execute this one.</p>
<h2 id="where-to-place-the-test-code">Where to place the test code</h2>
<p>The <code class="highlighter-rouge">PmdRuleTst</code> class searches the XML file, that describes the test cases for a certain rule
using the following convention:
The XML file is a test resource, so it is searched in the tree under <code class="highlighter-rouge">src/test/resources</code>.</p>
<p>The sub package <code class="highlighter-rouge">xml</code> of the test classs package should contain a file with the same name as the rules name
which is under test.</p>
<p>For example, to test the rule “AbstractClassWithoutAbstractMethod”, the fully qualified test class is:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>net.sourceforge.pmd.lang.java.rule.bestpractices.AbstractClassWithoutAbstractMethodTest
</code></pre></div></div>
<p>The test code for the rule can be found in the file:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/AbstractClassWithoutAbstractMethod.xml
</code></pre></div></div>
<p>In general, the class name and file name pattern for the test class and data is this:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>net.sourceforge.pmd.lang.&lt;Language Terse Name&gt;.rule.&lt;Category Name&gt;.&lt;Rule Name&gt;Test
src/test/resources/net/sourceforge/pmd/lang/&lt;Language Terse Name&gt;/rule/&lt;Category Name&gt;/xml/&lt;Rule Name&gt;.xml
</code></pre></div></div>
<div class="alert alert-success" role="alert"><i class="fa fa-check-square-o"></i> <b>Tip:</b> This convention allows you to quickly find the test cases for a given rule:
Just search in the project for a file <code class="highlighter-rouge">&lt;RuleName&gt;.xml</code>. Search for a class <code class="highlighter-rouge">&lt;Rule Name&gt;Test</code> to find the
unit test class for the given rule.</div>
<div class="alert alert-info" role="alert"><i class="fa fa-info-circle"></i> <b>Note:</b> If you want to use the test framework with a different package structure,
see <a href="#using-the-test-framework-externally">Using the test framework externally</a>.</div>
<h2 id="simple-example">Simple example</h2>
<h3 id="test-class-abstractclasswithoutabstractmethodtest">Test Class: AbstractClassWithoutAbstractMethodTest</h3>
<p>This class inherits from <code class="highlighter-rouge">PmdRuleTst</code> and is located in the package “bestpractices”, since the rule
belongs to the category “Best Practices”:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="n">net</span><span class="o">.</span><span class="na">sourceforge</span><span class="o">.</span><span class="na">pmd</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">java</span><span class="o">.</span><span class="na">rule</span><span class="o">.</span><span class="na">bestpractices</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">net.sourceforge.pmd.testframework.PmdRuleTst</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">AbstractClassWithoutAbstractMethodTest</span> <span class="kd">extends</span> <span class="n">PmdRuleTst</span> <span class="o">{</span>
<span class="c1">// no additional unit tests</span>
<span class="o">}</span>
</code></pre></div></div>
<div class="alert alert-info" role="alert"><i class="fa fa-info-circle"></i> <b>Note:</b> You can also add additionally standard JUnit test methods annotated with <code class="highlighter-rouge">@Test</code> to
this test class.</div>
<h3 id="test-data-avoidbranchingstatementaslastinloopxml">Test Data: AvoidBranchingStatementAsLastInLoop.xml</h3>
<p>This is a stripped down example which just contains two test cases.</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="nt">&lt;test-data</span>
<span class="na">xmlns=</span><span class="s">"http://pmd.sourceforge.net/rule-tests"</span>
<span class="na">xmlns:xsi=</span><span class="s">"http://www.w3.org/2001/XMLSchema-instance"</span>
<span class="na">xsi:schemaLocation=</span><span class="s">"http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd"</span><span class="nt">&gt;</span>
<span class="nt">&lt;test-code&gt;</span>
<span class="nt">&lt;description&gt;</span>concrete class<span class="nt">&lt;/description&gt;</span>
<span class="nt">&lt;expected-problems&gt;</span>0<span class="nt">&lt;/expected-problems&gt;</span>
<span class="nt">&lt;code&gt;</span><span class="cp">&lt;![CDATA[
public class Foo {}
]]&gt;</span><span class="nt">&lt;/code&gt;</span>
<span class="nt">&lt;/test-code&gt;</span>
<span class="nt">&lt;test-code&gt;</span>
<span class="nt">&lt;description&gt;</span>failure case<span class="nt">&lt;/description&gt;</span>
<span class="nt">&lt;expected-problems&gt;</span>1<span class="nt">&lt;/expected-problems&gt;</span>
<span class="nt">&lt;expected-linenumbers&gt;</span>1<span class="nt">&lt;/expected-linenumbers&gt;</span>
<span class="nt">&lt;code&gt;</span><span class="cp">&lt;![CDATA[
public abstract class Foo {}
]]&gt;</span><span class="nt">&lt;/code&gt;</span>
<span class="nt">&lt;/test-code&gt;</span>
<span class="nt">&lt;/test-data&gt;</span>
</code></pre></div></div>
<p>Each test case is in an own <code class="highlighter-rouge">&lt;test-code&gt;</code> element. The first defines 0 expected problems, means this code doesnt
trigger the rule. The second test case expects 1 problem. Since the rule violations also report the exact AST node,
you can verify the line number, too.</p>
<h2 id="test-xml-reference">Test XML Reference</h2>
<p>The root element is <code class="highlighter-rouge">&lt;test-data&gt;</code>. It can contain one or more <code class="highlighter-rouge">&lt;test-code&gt;</code> and <code class="highlighter-rouge">&lt;code-fragment&gt;</code> elements.
Each <code class="highlighter-rouge">&lt;test-code&gt;</code> element defines a single test case. <code class="highlighter-rouge">&lt;code-fragment&gt;</code> elements are used to share code snippets
between different test cases.</p>
<div class="alert alert-info" role="alert"><i class="fa fa-info-circle"></i> <b>Note:</b> The XML schema is available at <a href="https://github.com/pmd/pmd/blob/master/pmd-test/src/main/resources/rule-tests_1_0_0.xsd">rule-tests.xsd</a>.</div>
<h3 id="test-code-attributes"><code class="highlighter-rouge">&lt;test-code&gt;</code> attributes</h3>
<p>The <code class="highlighter-rouge">&lt;test-code&gt;</code> elements understands three optional attributes:</p>
<ul>
<li>
<p><strong>reinitializeRule</strong>: By default, its <code class="highlighter-rouge">true</code>, so each test case starts with a fresh instantiated rule. Set it
to <code class="highlighter-rouge">false</code> to reproduce cases, where the previous run has influences.</p>
</li>
<li>
<p><strong>regressionTest</strong>: By default, its <code class="highlighter-rouge">true</code>. Set it to <code class="highlighter-rouge">false</code>, to ignore and skip a test case.</p>
</li>
<li>
<p><strong>useAuxClasspath</strong>: By default, its <code class="highlighter-rouge">true</code>. Set it to <code class="highlighter-rouge">false</code> to reproduce issues which only
appear without type resolution.</p>
</li>
</ul>
<h3 id="test-code-children"><code class="highlighter-rouge">&lt;test-code&gt;</code> children</h3>
<ul>
<li>
<p><strong><code class="highlighter-rouge">&lt;description&gt;</code></strong>: Short description of the test case. This will be the JUnit test name in the report.
If applicable, this description should contain a reference to the bug number, this test case reproduces.</p>
</li>
<li>
<p><strong><code class="highlighter-rouge">&lt;rule-property&gt;</code></strong>: Optional rule properties, if the rule is configurable. Just add multiple elements, to
set multiple properties for one test case. For an example, see below.</p>
</li>
<li>
<p><strong><code class="highlighter-rouge">&lt;expected-problems&gt;</code></strong>: The the raw number of expected rule violations, that this rule is expected to report.
For false-positive test cases, this is always “0”. For false-negative test cases, it can be any positive number.</p>
</li>
<li>
<p><strong><code class="highlighter-rouge">&lt;expected-linenumbers&gt;</code></strong>: Optional element. Its a comma separated list of line numbers.
If there are rule violations reported, then this allows you to
assert the line numbers. Useful if multiple violations should be detected and to be sure that
false positives and negatives dont erase each other.</p>
</li>
<li>
<p><strong><code class="highlighter-rouge">&lt;expected-messages&gt;</code></strong>: Optional element, with <code class="highlighter-rouge">&lt;message&gt;</code> elements as children.
Can be used to validate the correct error message, e.g. if the error message references a variable name.</p>
</li>
<li>
<p><strong><code class="highlighter-rouge">&lt;code&gt;</code></strong>: Either the <code class="highlighter-rouge">&lt;code&gt;</code> element or the <code class="highlighter-rouge">&lt;code-ref&gt;</code> element is required. It provides the actual code
snippet on which the rule is executed. The code itself is usually wrapped in a “CDATA” section, so that no
further XML escapes (entity references such as &amp;lt;) are necessary.</p>
</li>
<li>
<p><strong><code class="highlighter-rouge">&lt;code-ref id=...&gt;</code></strong>: Alternative to <code class="highlighter-rouge">&lt;code&gt;</code>. References a <code class="highlighter-rouge">&lt;code-fragment&gt;</code> defined earlier in the file.
This allows you to share the same code snippet with several test cases. The attribute <code class="highlighter-rouge">id</code> must match the
id of the references code fragment.</p>
</li>
<li>
<p><strong><code class="highlighter-rouge">&lt;source-type&gt;</code></strong>: Optional element that specifies the source code language. This defines the parser that
is used for parsing the code snippet. If not given, <strong>java</strong> is used as default.</p>
</li>
</ul>
<h3 id="code-fragment"><code class="highlighter-rouge">&lt;code-fragment&gt;</code></h3>
<p>The code fragment has just one required attribute: <strong>id</strong>. This is used to reference it via a <code class="highlighter-rouge">&lt;code-ref&gt;</code> element
inside a <code class="highlighter-rouge">&lt;test-code&gt;</code>. Similar like the <code class="highlighter-rouge">&lt;code&gt;</code> element, the content of <code class="highlighter-rouge">&lt;code-fragment&gt;</code> is usually wrapped
in a “CDATA” section, so that no further XML escapes (entity references such as &amp;lt;) are necessary.</p>
<h3 id="complete-xml-example">Complete XML example</h3>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="nt">&lt;test-data</span>
<span class="na">xmlns=</span><span class="s">"http://pmd.sourceforge.net/rule-tests"</span>
<span class="na">xmlns:xsi=</span><span class="s">"http://www.w3.org/2001/XMLSchema-instance"</span>
<span class="na">xsi:schemaLocation=</span><span class="s">"http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd"</span><span class="nt">&gt;</span>
<span class="nt">&lt;test-code</span> <span class="na">reinitializeRule=</span><span class="s">"true"</span> <span class="na">regressionTest=</span><span class="s">"true"</span> <span class="na">useAuxClasspath=</span><span class="s">"true"</span><span class="nt">&gt;</span>
<span class="nt">&lt;description&gt;</span>Just a description, will be used as the test name for JUnit in the reports<span class="nt">&lt;/description&gt;</span>
<span class="nt">&lt;rule-property</span> <span class="na">name=</span><span class="s">"somePropName"</span><span class="nt">&gt;</span>propValue<span class="nt">&lt;/rule-property&gt;</span> <span class="c">&lt;!-- optional --&gt;</span>
<span class="nt">&lt;expected-problems&gt;</span>2<span class="nt">&lt;/expected-problems&gt;</span>
<span class="nt">&lt;expected-linenumbers&gt;</span>5,14<span class="nt">&lt;/expected-linenumbers&gt;</span> <span class="c">&lt;!-- optional --&gt;</span>
<span class="nt">&lt;expected-messages&gt;</span> <span class="c">&lt;!-- optional --&gt;</span>
<span class="nt">&lt;message&gt;</span>Violation message 1<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;message&gt;</span>Violation message 2<span class="nt">&lt;/message&gt;</span>
<span class="nt">&lt;/expected-messages&gt;</span>
<span class="nt">&lt;code&gt;</span><span class="cp">&lt;![CDATA[
public class ConsistentReturn {
public Boolean foo() {
}
}
]]&gt;</span><span class="nt">&lt;/code&gt;</span>
<span class="nt">&lt;source-type&gt;</span>apex<span class="nt">&lt;/source-type&gt;</span> <span class="c">&lt;!-- optional --&gt;</span>
<span class="nt">&lt;/test-code&gt;</span>
<span class="nt">&lt;code-fragment</span> <span class="na">id=</span><span class="s">"codeSnippet1"</span><span class="nt">&gt;</span><span class="cp">&lt;![CDATA[
public class ConsistentReturn {
public Boolean foo() {
}
}
]]&gt;</span><span class="nt">&lt;/code-fragment&gt;</span>
<span class="nt">&lt;test-code&gt;</span>
<span class="nt">&lt;description&gt;</span>test case using a code fragment<span class="nt">&lt;/description&gt;</span>
<span class="nt">&lt;expected-problems&gt;</span>0<span class="nt">&lt;/expected-problems&gt;</span>
<span class="nt">&lt;code-ref</span> <span class="na">id=</span><span class="s">"codeSnippet1"</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/test-code&gt;</span>
<span class="nt">&lt;/test-data&gt;</span>
</code></pre></div></div>
<h2 id="using-the-test-framework-externally">Using the test framework externally</h2>
<p>It is also possible to use the test framework for custom rules developed outside the PMD source base.
Therefore you just need to reference the dependency <code class="highlighter-rouge">net.sourceforge.pmd:pmd-test</code>.</p>
<p>For maven, you can use this snippet:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;dependency&gt;
&lt;groupId&gt;net.sourceforge.pmd&lt;/groupId&gt;
&lt;artifactId&gt;pmd-test&lt;/artifactId&gt;
&lt;version&gt;6.10.0&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre></div></div>
<p>Then proceed as described earlier: create your test class, create your test cases and run the unit test.</p>
<p>There is one difference however: Since your package structure is probably different, youll need to register
the rule test manually, as SimpleAggregatorTst will fail to determine it correctly from the package and class names:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="n">com</span><span class="o">.</span><span class="na">example</span><span class="o">.</span><span class="na">pmd</span><span class="o">.</span><span class="na">rules</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">net.sourceforge.pmd.testframework.SimpleAggregatorTst</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">CustomRuleTest</span> <span class="kd">extends</span> <span class="n">SimpleAggregatorTst</span> <span class="o">{</span>
<span class="nd">@Override</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">setUp</span><span class="o">()</span> <span class="o">{</span>
<span class="n">addRule</span><span class="o">(</span><span class="s">"com/example/pmd/ruleset.xml"</span><span class="o">,</span> <span class="s">"CustomRule"</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>This will then search for a rule named “CustomRule” in the ruleset, that is located in “src/main/resources” under
the path “com/example/pmd/ruleset.xml”.</p>
<p>The test data should be placed in an xml file located in “src/test/resources” under the path
“com/example/pmd/rules/xml/CustomRule.xml”.</p>
<h2 id="how-the-test-framework-is-implemented">How the test framework is implemented</h2>
<p>The framework uses a custom JUnit test runner under the hood, among a couple of utility classes:</p>
<ul>
<li>
<p><code class="highlighter-rouge">PmdRuleTst</code>: This is the base class for tests in PMDs code base. It is a subclass of <code class="highlighter-rouge">RuleTst</code> and just
contains the logic to determine the test resources based on the test class name.</p>
</li>
<li>
<p><code class="highlighter-rouge">SimpleAggregatorTst</code>: This is a more generic base class for the test classes and defines
the custom JUnit test runner. It doesnt register any test cases on its own.
It itself is a subclass of <code class="highlighter-rouge">RuleTst</code>.</p>
</li>
<li>
<p><code class="highlighter-rouge">RuleTst</code>: contains the logic to parse the XML files and provide a list of <code class="highlighter-rouge">TestDescriptor</code>s. Each test descriptor
describes a single test case. It also contains the logic to execute such a test descriptor and assert the results.</p>
</li>
<li>
<p><code class="highlighter-rouge">PMDTestRunner</code>: A custom JUnit test runner, that combines two separate test runners: The custom <code class="highlighter-rouge">RuleTestRunner</code>
and the standard <code class="highlighter-rouge">JUnit4</code> test runner. This combination allows you to add additional standard unit test methods
annotated with <code class="highlighter-rouge">@Test</code> to your test class.</p>
<p><em>Note:</em> Since the test class is executed through two test runners, it is actually instantiated twice. Be aware
of this, if you do any initialization in the constructor. Also, the static hooks <code class="highlighter-rouge">@BeforeClass</code> and <code class="highlighter-rouge">@AfterClass</code>
will be executed twice.</p>
</li>
<li>
<p><code class="highlighter-rouge">RuleTestRunner</code>: This test runner executes the test descriptors with the help of <code class="highlighter-rouge">RuleTst</code>.</p>
</li>
</ul>
<div class="tags">
<b>Tags: </b>
<a href="tag_extending.html" class="btn btn-default navbar-btn cursorNorm" role="button">extending</a>
<a href="tag_userdocs.html" class="btn btn-default navbar-btn cursorNorm" role="button">userdocs</a>
</div>
</div>
<hr class="shaded"/>
<footer>
<div class="row">
<div class="col-lg-12 footer">
&copy;2018 PMD Open Source Project. All rights reserved. <br />
<span>Page last updated:</span> November 2018<br/> Site last generated: Nov 11, 2018 <br />
<p><img src="images/pmd-logo-small.png" alt="Company logo"/></p>
</div>
</div>
</footer>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
</div>
</body>
</html>