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

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