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 28 KiB

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