You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tutorial-writing-tasks.html 29 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. <!DOCTYPE html>
  2. <!--
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. https://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. -->
  16. <html lang="en">
  17. <head>
  18. <title>Tutorial: Writing Tasks</title>
  19. <link rel="stylesheet" type="text/css" href="stylesheets/style.css"/>
  20. </head>
  21. <body>
  22. <h1>Tutorial: Writing Tasks</h1>
  23. <p>This document provides a step by step tutorial for writing
  24. tasks.</p>
  25. <h2>Content</h2>
  26. <ul>
  27. <li><a href="#buildenvironment">Set up the build environment</a></li>
  28. <li><a href="#write1">Write the Task</a></li>
  29. <li><a href="#use1">Use the Task</a></li>
  30. <li><a href="#TaskAdapter">Integration with TaskAdapter</a></li>
  31. <li><a href="#derivingFromTask">Deriving from Apache Ant's Task</a></li>
  32. <li><a href="#accessTaskProject">Accessing the Task's Project</a></li>
  33. <li><a href="#attributes">Attributes</a></li>
  34. <li><a href="#NestedText">Nested Text</a></li>
  35. <li><a href="#NestedElements">Nested Elements</a></li>
  36. <li><a href="#complex">Our task in a little more complex version</a></li>
  37. <li><a href="#TestingTasks">Test the Task</a></li>
  38. <li><a href="#Debugging">Debugging</a></li>
  39. <li><a href="#resources">Resources</a></li>
  40. </ul>
  41. <h2 id="buildenvironment">Set up the build environment</h2>
  42. <p>Apache Ant builds itself, we are using Ant too (why we would write a task if not? :-) therefore we should use Ant for
  43. our build.</p>
  44. <p>We choose a directory as root directory. All things will be done here if I say nothing different. I will reference
  45. this directory as <em>root-directory</em> of our project. In this root-directory we create a text file
  46. names <samp>build.xml</samp>. What should Ant do for us?</p>
  47. <ul>
  48. <li>compiles my stuff</li>
  49. <li>make the jar, so that I can deploy it</li>
  50. <li>clean up everything</li>
  51. </ul>
  52. So the buildfile contains three targets.
  53. <pre>
  54. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  55. &lt;project name="MyTask" basedir="." default="jar"&gt;
  56. &lt;target name="clean" description="Delete all generated files"&gt;
  57. &lt;delete dir="classes"/&gt;
  58. &lt;delete file="MyTasks.jar"/&gt;
  59. &lt;/target&gt;
  60. &lt;target name="compile" description="Compiles the Task"&gt;
  61. &lt;javac srcdir="src" destdir="classes"/&gt;
  62. &lt;/target&gt;
  63. &lt;target name="jar" description="JARs the Task"&gt;
  64. &lt;jar destfile="MyTask.jar" basedir="classes"/&gt;
  65. &lt;/target&gt;
  66. &lt;/project&gt;</pre>
  67. This buildfile uses often the same value (<samp>src</samp>, <samp>classes</samp>, <samp>MyTask.jar</samp>), so we should
  68. rewrite that using <code>&lt;property&gt;</code>s. On second there are some handicaps: <code>&lt;javac&gt;</code>
  69. requires that the destination directory exists; a call of <q>clean</q> with a non existing classes directory will
  70. fail; <q>jar</q> requires the execution of some steps before. So the refactored code is:
  71. <pre>
  72. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  73. &lt;project name="MyTask" basedir="." default="jar"&gt;
  74. <b>&lt;property name="src.dir" value="src"/&gt;</b>
  75. <b>&lt;property name="classes.dir" value="classes"/&gt;</b>
  76. &lt;target name="clean" description="Delete all generated files"&gt;
  77. &lt;delete dir="<b>${classes.dir}</b>" <b>failonerror="false"</b>/&gt;
  78. &lt;delete file="<b>${ant.project.name}.jar</b>"/&gt;
  79. &lt;/target&gt;
  80. &lt;target name="compile" description="Compiles the Task"&gt;
  81. <b>&lt;mkdir dir="${classes.dir}"/&gt;</b>
  82. &lt;javac srcdir="<b>${src.dir}</b>" destdir="${classes.dir}"/&gt;
  83. &lt;/target&gt;
  84. &lt;target name="jar" description="JARs the Task" <b>depends="compile"</b>&gt;
  85. &lt;jar destfile="${ant.project.name}.jar" basedir="${classes.dir}"/&gt;
  86. &lt;/target&gt;
  87. &lt;/project&gt;</pre>
  88. <p><code>ant.project.name</code> is one of the <a href="properties.html#built-in-props" target="_top">build-in
  89. properties [1]</a> of Ant.</p>
  90. <h2 id="write1">Write the Task</h2>
  91. <p>Now we write the simplest Task&mdash;a HelloWorld Task (what else?). Create a text file <samp>HelloWorld.java</samp>
  92. in the src-directory with:</p>
  93. <pre>
  94. public class HelloWorld {
  95. public void execute() {
  96. System.out.println("Hello World");
  97. }
  98. }</pre>
  99. <p>and we can compile and jar it with <kbd>ant</kbd> (default target is <q>jar</q> and via its <var>depends</var>
  100. attribute the <q>compile</q> is executed before).</p>
  101. <h2 id="use1">Use the Task</h2>
  102. <p>But after creating the jar we want to use our new Task. Therefore we need a new target <q>use</q>. Before we can use
  103. our new task we have to declare it with <a href="Tasks/taskdef.html" target="_top"><code>&lt;taskdef&gt;</code>
  104. [2]</a>. And for easier process we change the <var>default</var> attribute:</p>
  105. <pre>
  106. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  107. &lt;project name="MyTask" basedir="." default="<b>use</b>"&gt;
  108. ...
  109. <b>&lt;target name="use" description="Use the Task" depends="jar"&gt;
  110. &lt;taskdef name="helloworld" classname="HelloWorld" classpath="${ant.project.name}.jar"/&gt;
  111. &lt;helloworld/&gt;
  112. &lt;/target&gt;</b>
  113. &lt;/project&gt;</pre>
  114. <p>Important is the <var>classpath</var> attribute. Ant searches in its <samp>/lib</samp> directory for tasks and our
  115. task isn't there. So we have to provide the right location.</p>
  116. <p>Now we can type in <kbd>ant</kbd> and all should work ...</p>
  117. <pre class="output">
  118. Buildfile: build.xml
  119. compile:
  120. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  121. [javac] Compiling 1 source file to C:\tmp\anttests\MyFirstTask\classes
  122. jar:
  123. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  124. use:
  125. [helloworld] Hello World
  126. BUILD SUCCESSFUL
  127. Total time: 3 seconds</pre>
  128. <h2 id="TaskAdapter">Integration with TaskAdapter</h2>
  129. <p>Our class has nothing to do with Ant. It extends no superclass and implements no interface. How does Ant know to
  130. integrate? Via name convention: our class provides a method with signature <code class="code">public void
  131. execute()</code>. This class is wrapped by Ant's <code class="code">org.apache.tools.ant.TaskAdapter</code> which is a
  132. task and uses reflection for setting a reference to the project and calling the <code class="code">execute()</code>
  133. method.</p>
  134. <p><em>Setting a reference to the project</em>? Could be interesting. The Project class gives us some nice abilities:
  135. access to Ant's logging facilities getting and setting properties and much more. So we try to use that class:</p>
  136. <pre>
  137. import org.apache.tools.ant.Project;
  138. public class HelloWorld {
  139. private Project project;
  140. public void setProject(Project proj) {
  141. project = proj;
  142. }
  143. public void execute() {
  144. String message = project.getProperty("ant.project.name");
  145. project.log("Here is project '" + message + "'.", Project.MSG_INFO);
  146. }
  147. }</pre>
  148. <p>and the execution with <kbd>ant</kbd> will show us the expected</p>
  149. <pre class="output">
  150. use:
  151. Here is project 'MyTask'.</pre>
  152. <h2 id="derivingFromTask">Deriving from Ant's Task</h2>
  153. <p>Ok, that works ... But usually you will extend <code class="code">org.apache.tools.ant.Task</code>. That class is
  154. integrated in Ant, gets the project reference, provides documentation fields, provides easier access to the logging
  155. facility and (very useful) gives you the exact location where <em>in the buildfile</em> this task instance is used.</p>
  156. <p>Oki-doki&mdash;let's us use some of these:</p>
  157. <pre>
  158. import org.apache.tools.ant.Task;
  159. public class HelloWorld extends Task {
  160. public void execute() {
  161. // use of the reference to Project-instance
  162. String message = getProject().getProperty("ant.project.name");
  163. // Task's log method
  164. log("Here is project '" + message + "'.");
  165. // where this task is used?
  166. log("I am used in: " + getLocation() );
  167. }
  168. }</pre>
  169. <p>which gives us when running</p>
  170. <pre class="output">
  171. use:
  172. [helloworld] Here is project 'MyTask'.
  173. [helloworld] I am used in: C:\tmp\anttests\MyFirstTask\build.xml:23:</pre>
  174. <h2 id="accessTaskProject">Accessing the Task's Project</h2>
  175. <p>The parent project of your custom task may be accessed through method <code class="code">getProject()</code>.
  176. However, do not call this from the custom task constructor, as the return value will be null. Later, when node
  177. attributes or text are set, or method <code class="code">execute()</code> is called, the Project object is
  178. available.</p>
  179. <p>Here are two useful methods from class Project:</p>
  180. <ul>
  181. <li><code class="code">String getProperty(String propertyName)</code></li>
  182. <li><code class="code">String replaceProperties(String value)</code></li>
  183. </ul>
  184. <p>The method <code class="code">replaceProperties()</code> is discussed further in section <a href="#NestedText">Nested
  185. Text</a>.</p>
  186. <h2 id="attributes">Attributes</h2>
  187. <p>Now we want to specify the text of our message (it seems that we are rewriting the <code>&lt;echo/&gt;</code> task
  188. :-). First we well do that with an attribute. It is very easy&mdash;for each attribute provide
  189. a <code class="code">public void set<i>Attributename</i>(<i>Type</i> newValue)</code> method and Ant will do the rest
  190. via reflection.</p>
  191. <pre>
  192. import org.apache.tools.ant.Task;
  193. import org.apache.tools.ant.BuildException;
  194. public class HelloWorld extends Task {
  195. String message;
  196. public void setMessage(String msg) {
  197. message = msg;
  198. }
  199. public void execute() {
  200. if (message == null) {
  201. throw new BuildException("No message set.");
  202. }
  203. log(message);
  204. }
  205. }</pre>
  206. <p>Oh, what's that in <code class="code">execute()</code>? Throw a <code>BuildException</code>? Yes, that's the usual
  207. way to show Ant that something important is missed and complete build should fail. The string provided there is written
  208. as build-fails-message. Here it's necessary because the <code class="code">log()</code> method can't handle
  209. a <code>null</code> value as parameter and throws a <code>NullPointerException</code>. (Of course you can initialize
  210. the <var>message</var> with a default string.)</p>
  211. <p>After that we have to modify our buildfile:</p>
  212. <pre>
  213. &lt;target name="use" description="Use the Task" depends="jar"&gt;
  214. &lt;taskdef name="helloworld"
  215. classname="HelloWorld"
  216. classpath="${ant.project.name}.jar"/&gt;
  217. &lt;helloworld <b>message="Hello World"</b>/&gt;
  218. &lt;/target&gt;</pre>
  219. <p>That's all.</p>
  220. <p>Some background for working with attributes: Ant supports any of these datatypes as arguments of the set-method:</p>
  221. <ul>
  222. <li>primitive data types like <code class="code">int</code>, <code class="code">long</code>, ...</li>
  223. <li>their wrapper classes like <code class="code">java.lang.Integer</code>, <code class="code">java.lang.Long</code>,
  224. ...</li>
  225. <li><code class="code">java.lang.String</code></li>
  226. <li>some other classes (e.g. <code class="code">java.io.File</code>; see <a href="develop.html#set-magic">Manual
  227. 'Writing Your Own Task' [3]</a>)</li>
  228. <li>Any Java Object parsed from Ant 1.8's <a href="Tasks/propertyhelper.html">Property
  229. Helper</a></li>
  230. </ul>
  231. <p>Before calling the set-method all properties are resolved. So a <code>&lt;helloworld message="${msg}"/&gt;</code>
  232. would not set the message string to <q>${msg}</q> if there is a property <code>msg</code> with a set value.</p>
  233. <h2 id="NestedText">Nested Text</h2>
  234. <p>Maybe you have used the <code>&lt;echo&gt;</code> task in a way like <code>&lt;echo&gt;Hello
  235. World&lt;/echo&gt;</code>. For that you have to provide a <code class="code">public void addText(String text)</code>
  236. method.</p>
  237. <pre>
  238. ...
  239. public class HelloWorld extends Task {
  240. private String message;
  241. ...
  242. public void addText(String text) {
  243. message = text;
  244. }
  245. ...
  246. }</pre>
  247. <p>But here properties are <strong>not</strong> resolved! For resolving properties we have to use
  248. Project's <code class="code">replaceProperties(String propname)</code> method which takes the property name as argument
  249. and returns its value (or <code>${propname}</code> if not set).</p>
  250. <p>Thus, to replace properties in the nested node text, our method <code class="code">addText()</code> can be written
  251. as:</p>
  252. <pre>
  253. public void addText(String text) {
  254. message = getProject().replaceProperties(text);
  255. }</pre>
  256. <h2 id="NestedElements">Nested Elements</h2>
  257. <p>There are several ways for inserting the ability of handling nested elements. See
  258. the <a href="develop.html#nested-elements">Manual [4]</a> for other. We use the first way of the three described
  259. ways. There are several steps for that:</p>
  260. <ol>
  261. <li>We create a class for collecting all the info the nested element should contain. This class is created by the same
  262. rules for attributes and nested elements as for the task (<code class="code">set<i>Attributename</i>()</code>
  263. methods).</li>
  264. <li>The task holds multiple instances of this class in a list.</li>
  265. <li>A factory method instantiates an object, saves the reference in the list and returns it to Ant Core.</li>
  266. <li>The <code class="code">execute()</code> method iterates over the list and evaluates its values.</li>
  267. </ol>
  268. <pre>
  269. import java.util.ArrayList;
  270. import java.util.List;
  271. ...
  272. public void execute() {
  273. if (message != null) log(message);
  274. for (Message msg : messages) { <b>// 4</b>
  275. log(msg.getMsg());
  276. }
  277. }
  278. List&lt;Message&gt; messages = new ArrayList&lt;&gt;(); <b>// 2</b>
  279. public Message createMessage() { <b>// 3</b>
  280. Message msg = new Message();
  281. messages.add(msg);
  282. return msg;
  283. }
  284. public class Message { <b>// 1</b>
  285. public Message() {}
  286. String msg;
  287. public void setMsg(String msg) { this.msg = msg; }
  288. public String getMsg() { return msg; }
  289. }
  290. ...</pre>
  291. <p>Then we can use the new nested element. But where is XML-name for that defined? The mapping XML-name &rarr;
  292. classname is defined in the factory method: <code class="code">public <i>classname</i>
  293. create<i>XML-name</i>()</code>. Therefore we write in the buildfile</p>
  294. <pre>
  295. &lt;helloworld&gt;
  296. &lt;message msg="Nested Element 1"/&gt;
  297. &lt;message msg="Nested Element 2"/&gt;
  298. &lt;/helloworld&gt;</pre>
  299. <p>Note that if you choose to use methods 2 or 3, the class that represents the nested element must be declared
  300. as <code>static</code></p>
  301. <h2 id="complex">Our task in a little more complex version</h2>
  302. <p>For recapitulation now a little refactored buildfile:</p>
  303. <pre>
  304. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  305. &lt;project name="MyTask" basedir="." default="use"&gt;
  306. &lt;property name="src.dir" value="src"/&gt;
  307. &lt;property name="classes.dir" value="classes"/&gt;
  308. &lt;target name="clean" description="Delete all generated files"&gt;
  309. &lt;delete dir="${classes.dir}" failonerror="false"/&gt;
  310. &lt;delete file="${ant.project.name}.jar"/&gt;
  311. &lt;/target&gt;
  312. &lt;target name="compile" description="Compiles the Task"&gt;
  313. &lt;mkdir dir="${classes.dir}"/&gt;
  314. &lt;javac srcdir="${src.dir}" destdir="${classes.dir}"/&gt;
  315. &lt;/target&gt;
  316. &lt;target name="jar" description="JARs the Task" depends="compile"&gt;
  317. &lt;jar destfile="${ant.project.name}.jar" basedir="${classes.dir}"/&gt;
  318. &lt;/target&gt;
  319. &lt;target name="use.init"
  320. description="Taskdef the HelloWorld-Task"
  321. depends="jar"&gt;
  322. &lt;taskdef name="helloworld"
  323. classname="HelloWorld"
  324. classpath="${ant.project.name}.jar"/&gt;
  325. &lt;/target&gt;
  326. &lt;target name="use.without"
  327. description="Use without any"
  328. depends="use.init"&gt;
  329. &lt;helloworld/&gt;
  330. &lt;/target&gt;
  331. &lt;target name="use.message"
  332. description="Use with attribute 'message'"
  333. depends="use.init"&gt;
  334. &lt;helloworld message="attribute-text"/&gt;
  335. &lt;/target&gt;
  336. &lt;target name="use.fail"
  337. description="Use with attribute 'fail'"
  338. depends="use.init"&gt;
  339. &lt;helloworld fail="true"/&gt;
  340. &lt;/target&gt;
  341. &lt;target name="use.nestedText"
  342. description="Use with nested text"
  343. depends="use.init"&gt;
  344. &lt;helloworld&gt;nested-text&lt;/helloworld&gt;
  345. &lt;/target&gt;
  346. &lt;target name="use.nestedElement"
  347. description="Use with nested 'message'"
  348. depends="use.init"&gt;
  349. &lt;helloworld&gt;
  350. &lt;message msg="Nested Element 1"/&gt;
  351. &lt;message msg="Nested Element 2"/&gt;
  352. &lt;/helloworld&gt;
  353. &lt;/target&gt;
  354. &lt;target name="use"
  355. description="Try all (w/out use.fail)"
  356. depends="use.without,use.message,use.nestedText,use.nestedElement"/&gt;
  357. &lt;/project&gt;</pre>
  358. <p>And the code of the task:</p>
  359. <pre>
  360. import org.apache.tools.ant.Task;
  361. import org.apache.tools.ant.BuildException;
  362. import java.util.ArrayList;
  363. import java.util.List;
  364. /**
  365. * The task of the tutorial.
  366. * Print a message or let the build fail.
  367. * @since 2003-08-19
  368. */
  369. public class HelloWorld extends Task {
  370. /** The message to print. As attribute. */
  371. String message;
  372. public void setMessage(String msg) {
  373. message = msg;
  374. }
  375. /** Should the build fail? Defaults to <i>false</i>. As attribute. */
  376. boolean fail = false;
  377. public void setFail(boolean b) {
  378. fail = b;
  379. }
  380. /** Support for nested text. */
  381. public void addText(String text) {
  382. message = text;
  383. }
  384. /** Do the work. */
  385. public void execute() {
  386. // handle attribute 'fail'
  387. if (fail) throw new BuildException("Fail requested.");
  388. // handle attribute 'message' and nested text
  389. if (message != null) log(message);
  390. // handle nested elements
  391. for (Message msg : messages) {
  392. log(msg.getMsg());
  393. }
  394. }
  395. /** Store nested 'message's. */
  396. List&lt;Message&gt; messages = new ArrayList&lt;&gt;();
  397. /** Factory method for creating nested 'message's. */
  398. public Message createMessage() {
  399. Message msg = new Message();
  400. messages.add(msg);
  401. return msg;
  402. }
  403. /** A nested 'message'. */
  404. public class Message {
  405. // Bean constructor
  406. public Message() {}
  407. /** Message to print. */
  408. String msg;
  409. public void setMsg(String msg) { this.msg = msg; }
  410. public String getMsg() { return msg; }
  411. }
  412. }</pre>
  413. <p>And it works:</p>
  414. <pre class="output">
  415. C:\tmp\anttests\MyFirstTask&gt;ant
  416. Buildfile: build.xml
  417. compile:
  418. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  419. [javac] Compiling 1 source file to C:\tmp\anttests\MyFirstTask\classes
  420. jar:
  421. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  422. use.init:
  423. use.without:
  424. use.message:
  425. [helloworld] attribute-text
  426. use.nestedText:
  427. [helloworld] nested-text
  428. use.nestedElement:
  429. [helloworld]
  430. [helloworld]
  431. [helloworld]
  432. [helloworld]
  433. [helloworld] Nested Element 1
  434. [helloworld] Nested Element 2
  435. use:
  436. BUILD SUCCESSFUL
  437. Total time: 3 seconds
  438. C:\tmp\anttests\MyFirstTask&gt;ant use.fail
  439. Buildfile: build.xml
  440. compile:
  441. jar:
  442. use.init:
  443. use.fail:
  444. BUILD FAILED
  445. C:\tmp\anttests\MyFirstTask\build.xml:36: Fail requested.
  446. Total time: 1 second
  447. C:\tmp\anttests\MyFirstTask&gt;</pre>
  448. <p>Next step: test ...</p>
  449. <h2 id="TestingTasks">Test the Task</h2>
  450. <p>We have written a test already: the <q>use.*</q> targets in the buildfile. But it's difficult to test that
  451. automatically. Commonly (and in Ant) JUnit is used for that. For testing tasks Ant provides a JUnit
  452. Rule <code class="code">org.apache.tools.ant.BuildFileRule</code>. This class provides some for testing tasks useful
  453. methods: initialize Ant, load a buildfile, execute targets, capture debug and run logs ...</p>
  454. <p>In Ant it is usual that the testcase has the same name as the task with a prepended <code>Test</code>, therefore we
  455. will create a file <samp>HelloWorldTest.java</samp>. Because we have a very small project we can put this file
  456. into <samp>src</samp> directory (Ant's own testclasses are in <samp>/src/testcases/...</samp>). Because we have already
  457. written our tests for "hand-test" we can use that for automatic tests, too. All test supporting classes are a part of
  458. the binary distribution of Ant <em>since Ant 1.7.0</em> in form of <samp>ant-testutil.jar</samp>. You can also build the
  459. jar file from source distro with target "test-jar".
  460. <p>For executing the test and creating a report we need the optional tasks <code>&lt;junit&gt;</code>
  461. and <code>&lt;junitreport&gt;</code>. So we add to the buildfile:</p>
  462. <pre>
  463. <span style="color:gray">&lt;project name="MyTask" basedir="." </span>default="test"<span style="color:gray">&gt;</span>
  464. ...
  465. &lt;property name="ant.test.lib" value="ant-testutil.jar"/&gt;
  466. &lt;property name="report.dir" value="report"/&gt;
  467. &lt;property name="junit.out.dir.xml" value="${report.dir}/junit/xml"/&gt;
  468. &lt;property name="junit.out.dir.html" value="${report.dir}/junit/html"/&gt;
  469. &lt;path id="classpath.run"&gt;
  470. &lt;path path="${java.class.path}"/&gt;
  471. &lt;path location="${ant.project.name}.jar"/&gt;
  472. &lt;/path&gt;
  473. &lt;path id="classpath.test"&gt;
  474. &lt;path refid="classpath.run"/&gt;
  475. &lt;path location="${ant.test.lib}"/&gt;
  476. &lt;/path&gt;
  477. &lt;target name="clean" description="Delete all generated files"&gt;
  478. &lt;delete failonerror="false" includeEmptyDirs="true"&gt;
  479. &lt;fileset dir="." includes="${ant.project.name}.jar"/&gt;
  480. &lt;fileset dir="${classes.dir}"/&gt;
  481. &lt;fileset dir="${report.dir}"/&gt;
  482. &lt;/delete&gt;
  483. &lt;/target&gt;
  484. <span style="color:gray">&lt;target name="compile" description="Compiles Vector the Task"&gt;
  485. &lt;mkdir dir="${classes.dir}"/&gt;
  486. &lt;javac srcdir="${src.dir}" destdir="${classes.dir}" </span>classpath="${ant.test.lib}"<span style="color:gray">/&gt;
  487. &lt;/target&gt;</span>
  488. ...
  489. &lt;target name="junit" description="Runs the unit tests" depends="jar"&gt;
  490. &lt;delete dir="${junit.out.dir.xml}"/&gt;
  491. &lt;mkdir dir="${junit.out.dir.xml}"/&gt;
  492. &lt;junit printsummary="yes" haltonfailure="no"&gt;
  493. &lt;classpath refid="classpath.test"/&gt;
  494. &lt;formatter type="xml"/&gt;
  495. &lt;batchtest fork="yes" todir="${junit.out.dir.xml}"&gt;
  496. &lt;fileset dir="${src.dir}" includes="**/*Test.java"/&gt;
  497. &lt;/batchtest&gt;
  498. &lt;/junit&gt;
  499. &lt;/target&gt;
  500. &lt;target name="junitreport" description="Create a report for the rest result"&gt;
  501. &lt;mkdir dir="${junit.out.dir.html}"/&gt;
  502. &lt;junitreport todir="${junit.out.dir.html}"&gt;
  503. &lt;fileset dir="${junit.out.dir.xml}"&gt;
  504. &lt;include name="*.xml"/&gt;
  505. &lt;/fileset&gt;
  506. &lt;report format="frames" todir="${junit.out.dir.html}"/&gt;
  507. &lt;/junitreport&gt;
  508. &lt;/target&gt;
  509. &lt;target name="test"
  510. depends="junit,junitreport"
  511. description="Runs unit tests and creates a report"/&gt;
  512. ...
  513. <span style="color:gray">&lt;/project&gt;</span></pre>
  514. <p>Back to the <samp>src/HelloWorldTest.java</samp>. We create a class with a
  515. public <code class="code">BuildFileRule</code> field annotated with JUnit's <code class="code">@Rule</code>
  516. annotation. As per conventional JUnit4 tests, this class should have no constructors, nor a default no-args constructor,
  517. setup methods should be annotated with <code class="code">@Before</code>, tear down methods annotated
  518. with <code class="code">@After</code> and any test method annotated with <code class="code">@Test</code>.
  519. <pre>
  520. import org.apache.tools.ant.BuildFileRule;
  521. import org.junit.Assert;
  522. import org.junit.Test;
  523. import org.junit.Before;
  524. import org.junit.Rule;
  525. import org.apache.tools.ant.AntAssert;
  526. import org.apache.tools.ant.BuildException;
  527. public class HelloWorldTest {
  528. @Rule
  529. public final BuildFileRule buildRule = new BuildFileRule();
  530. @Before
  531. public void setUp() {
  532. // initialize Ant
  533. buildRule.configureProject("build.xml");
  534. }
  535. @Test
  536. public void testWithout() {
  537. buildRule.executeTarget("use.without");
  538. assertEquals("Message was logged but should not.", buildRule.getLog(), "");
  539. }
  540. public void testMessage() {
  541. // execute target 'use.nestedText' and expect a message
  542. // 'attribute-text' in the log
  543. buildRule.executeTarget("use.message");
  544. Assert.assertEquals("attribute-text", buildRule.getLog());
  545. }
  546. @Test
  547. public void testFail() {
  548. // execute target 'use.fail' and expect a BuildException
  549. // with text 'Fail requested.'
  550. try {
  551. buildRule.executeTarget("use.fail");
  552. fail("BuildException should have been thrown as task was set to fail");
  553. } catch (BuildException ex) {
  554. Assert.assertEquals("fail requested", ex.getMessage());
  555. }
  556. }
  557. @Test
  558. public void testNestedText() {
  559. buildRule.executeTarget("use.nestedText");
  560. Assert.assertEquals("nested-text", buildRule.getLog());
  561. }
  562. @Test
  563. public void testNestedElement() {
  564. buildRule.executeTarget("use.nestedElement");
  565. AntAssert.assertContains("Nested Element 1", buildRule.getLog());
  566. AntAssert.assertContains("Nested Element 2", buildRule.getLog());
  567. }
  568. }</pre>
  569. <p>When starting <kbd>ant</kbd> we'll get a short message to STDOUT and a nice HTML report.</p>
  570. <pre class="output">
  571. C:\tmp\anttests\MyFirstTask&gt;ant
  572. Buildfile: build.xml
  573. compile:
  574. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  575. [javac] Compiling 2 source files to C:\tmp\anttests\MyFirstTask\classes
  576. jar:
  577. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  578. junit:
  579. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\report\junit\xml
  580. [junit] Running HelloWorldTest
  581. [junit] Tests run: 5, Failures: 0, Errors: 0, Time elapsed: 2,334 sec
  582. junitreport:
  583. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\report\junit\html
  584. [junitreport] Using Xalan version: Xalan Java 2.4.1
  585. [junitreport] Transform time: 661ms
  586. test:
  587. BUILD SUCCESSFUL
  588. Total time: 7 seconds
  589. C:\tmp\anttests\MyFirstTask&gt;</pre>
  590. <h2 id="Debugging">Debugging</h2>
  591. <p>Try running Ant with the flag <kbd>-verbose</kbd>. For more information, try flag <kbd>-debug</kbd>.</p>
  592. <p>For deeper issues, you may need to run the custom task code in a Java debugger. First, get the source for Ant and
  593. build it with debugging information.</p>
  594. <p>Since Ant is a large project, it can be a little tricky to set the right breakpoints. Here are two important
  595. breakpoints for version 1.8:</p>
  596. <ul>
  597. <li>Initial <code class="code">main()</code>
  598. function: <code class="code">com.apache.tools.ant.launch.Launcher.main()</code></li>
  599. <li>Task entry point: <code class="code">com.apache.tools.ant.UnknownElement.execute()</code></li>
  600. </ul>
  601. <p>If you need to debug when a task attribute or the text is set, begin by debugging into
  602. method <code class="code">execute()</code> of your custom task. Then set breakpoints in other methods. This will
  603. ensure the class bytecode has been loaded by JVM.</p>
  604. <h2 id="resources">Resources</h2>
  605. <p>This tutorial and its resources are available via <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=22570"
  606. target="_top">BugZilla [5]</a>. The ZIP provided there contains</p>
  607. <ul>
  608. <li>this initial version of this tutorial</li>
  609. <li>the buildfile (last version)</li>
  610. <li>the source of the task (last version)</li>
  611. <li>the source of the unit test (last version)</li>
  612. <li>the ant-testutil.jar (nightly build of 2003-08-18)</li>
  613. <li>generated classes</li>
  614. <li>generated jar</li>
  615. <li>generated reports</li>
  616. </ul>
  617. <p>The last sources and the buildfile are also available <a href="tutorial-writing-tasks-src.zip">here [6]</a> inside
  618. the manual.</p>
  619. <p>Used Links:</p>
  620. <ol class="refs">
  621. <li><a href="properties.html#built-in-props">https://ant.apache.org/manual/properties.html#built-in-props</a></li>
  622. <li><a href="Tasks/taskdef.html">https://ant.apache.org/manual/Tasks/taskdef.html</a></li>
  623. <li><a href="develop.html#set-magic">https://ant.apache.org/manual/develop.html#set-magic</a></li>
  624. <li><a href="develop.html#nested-elements">https://ant.apache.org/manual/develop.html#nested-elements</a></li>
  625. <li><a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=22570"
  626. target="_top">https://issues.apache.org/bugzilla/show_bug.cgi?id=22570</a></li>
  627. <li><a href="tutorial-writing-tasks-src.zip">tutorial-writing-tasks-src.zip</a></li>
  628. </ol>
  629. </body>
  630. </html>