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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. <p><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 Ant's Task</a></li>
  31. <li><a href="#attributes">Attributes</a></li>
  32. <li><a href="#NestedText">Nested Text</a></li>
  33. <li><a href="#NestedElements">Nested Elements</a></li>
  34. <li><a href="#complex">Our task in a little more complex version</a></li>
  35. <li><a href="#TestingTasks">Test the Task</a></li>
  36. <li><a href="#resources">Resources</a></li>
  37. </ul></p>
  38. <a name="buildenvironment"></a>
  39. <h2>Set up the build environment</h2>
  40. <p>Ant builds itself, we are using Ant too (why we would write
  41. a task if not? :-) therefore we should use Ant for our build.<p>
  42. <p>We choose a directory as root directory. All things will be done
  43. here if I say nothing different. I will reference this directory
  44. as <i>root-directory</i> of our project. In this root-directory we
  45. create a text file names <i>build.xml</i>. What should Ant do for us?
  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="ISO-8859-1"?&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;
  66. </pre>
  67. This buildfile uses often the same value (src, classes, MyTask.jar), so we should rewrite that
  68. using <code>&lt;property&gt;</code>s. On second there are some handicaps: <code>&lt;javac&gt;</code> requires that the destination
  69. directory exists; a call of "clean" with a non existing classes directory will fail; "jar" requires
  70. the execution of some steps bofore. So the refactored code is:
  71. <pre class="code">
  72. &lt;?xml version="1.0" encoding="ISO-8859-1"?&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;
  88. </pre>
  89. <i>ant.project.name</i> is one of the
  90. <a href="http://ant.apache.org/manual/using.html#built-in-props" target="_blank">
  91. build-in properties [1]</a> of Ant.
  92. <a name="write1"></a>
  93. <h2>Write the Task</h2>
  94. Now we write the simplest Task - a HelloWorld-Task (what else?). Create a text file
  95. <i>HelloWorld.java</i> in the src-directory with:
  96. <pre class="code">
  97. public class HelloWorld {
  98. public void execute() {
  99. System.out.println("Hello World");
  100. }
  101. }
  102. </pre>
  103. and we can compile and jar it with <tt>ant</tt> (default target is "jar" and via
  104. its <i>depends</i>-clause the "compile" is executed before).
  105. <a name="use1"></a>
  106. <h2>Use the Task</h2>
  107. <p>But after creating the jar we want to use our new Task. Therefore we need a
  108. new target "use". Before we can use our new task we have to declare it with
  109. <a href="http://ant.apache.org/manual/CoreTasks/taskdef.html" target="_blank">
  110. <code>&lt;taskdef&gt;</code> [2]</a>. And for easier process we change the default clause:
  111. <pre class="code">
  112. &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  113. &lt;project name="MyTask" basedir="." default="<b>use</b>"&gt;
  114. ...
  115. <b>&lt;target name="use" description="Use the Task" depends="jar"&gt;
  116. &lt;taskdef name="helloworld" classname="HelloWorld" classpath="${ant.project.name}.jar"/&gt;
  117. &lt;helloworld/&gt;
  118. &lt;/target&gt;</b>
  119. &lt;/project&gt;
  120. </pre>
  121. Important is the <i>classpath</i>-attribute. Ant searches in its /lib directory for
  122. tasks and our task isn't there. So we have to provide the right location. </p>
  123. <p>Now we can type in <tt>ant</tt> and all should work ...
  124. <pre class="output">
  125. Buildfile: build.xml
  126. compile:
  127. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  128. [javac] Compiling 1 source file to C:\tmp\anttests\MyFirstTask\classes
  129. jar:
  130. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  131. use:
  132. [helloworld] Hello World
  133. BUILD SUCCESSFUL
  134. Total time: 3 seconds
  135. </pre>
  136. <a name="TaskAdapter"></a>
  137. <h2>Integration with TaskAdapter</h2>
  138. <p>Our class has nothing to do with Ant. It extends no superclass and implements
  139. no interface. How does Ant know to integrate? Via name convention: our class provides
  140. a method with signature <tt>public void execute()</tt>. This class is wrapped by Ant's
  141. <tt>org.apache.tools.ant.TaskAdapter</tt> which is a task and uses reflection for
  142. setting a reference to the project and calling the <i>execute()</i> method.</p>
  143. <p><i>Setting a reference to the project</i>? Could be interesting. The Project class
  144. gives us some nice abilities: access to Ant's logging facilities getting and setting
  145. properties and much more. So we try to use that class:
  146. <pre class="code">
  147. import org.apache.tools.ant.Project;
  148. public class HelloWorld {
  149. private Project project;
  150. public void setProject(Project proj) {
  151. project = proj;
  152. }
  153. public void execute() {
  154. String message = project.getProperty("ant.project.name");
  155. project.log("Here is project '" + message + "'.", Project.MSG_INFO);
  156. }
  157. }
  158. </pre>
  159. and the execution with <tt>ant</tt> will show us the expected
  160. <pre class="output">
  161. use:
  162. Here is project 'MyTask'.
  163. </pre></p>
  164. <a name="derivingFromTask"></a>
  165. <h2>Deriving from Ant's Task</h2>
  166. <p>Ok, that works ... But usually you will extend <tt>org.apache.tools.ant.Task</tt>.
  167. That class is integrated in Ant, get's the project-reference, provides documentation
  168. fiels, provides easier access to the logging facility and (very useful) gives you
  169. the exact location where <i>in the buildfile</i> this task instance is used.</p>
  170. <p>Oki-doki - let's us use some of these:
  171. <pre class="code">
  172. import org.apache.tools.ant.Task;
  173. public class HelloWorld extends Task {
  174. public void execute() {
  175. // use of the reference to Project-instance
  176. String message = getProject().getProperty("ant.project.name");
  177. // Task's log method
  178. log("Here is project '" + message + "'.");
  179. // where this task is used?
  180. log("I am used in: " + getLocation() );
  181. }
  182. }
  183. </pre>
  184. which gives us when running
  185. <pre class="output">
  186. use:
  187. [helloworld] Here is project 'MyTask'.
  188. [helloworld] I am used in: C:\tmp\anttests\MyFirstTask\build.xml:23:
  189. </pre>
  190. <a name="attributes">
  191. <h2>Attributes</h2>
  192. <p>Now we want to specify the text of our message (it seems that we are
  193. rewriting the <code>&lt;echo/&gt;</code> task :-). First we well do that with an attribute.
  194. It is very easy - for each attribute provide a <tt>public void set<code>&lt;attributename&gt;</code>(<code>&lt;type&gt;</code>
  195. newValue)</tt> method and Ant will do the rest via reflection.</p>
  196. <pre class="code">
  197. import org.apache.tools.ant.Task;
  198. import org.apache.tools.ant.BuildException;
  199. public class HelloWorld extends Task {
  200. String message;
  201. public void setMessage(String msg) {
  202. message = msg;
  203. }
  204. public void execute() {
  205. if (message==null) {
  206. throw new BuildException("No message set.");
  207. }
  208. log(message);
  209. }
  210. }
  211. </pre>
  212. <p>Oh, what's that in execute()? Throw a <i>BuildException</i>? Yes, that's the usual
  213. way to show Ant that something important is missed and complete build should fail. The
  214. string provided there is written as build-failes-message. Here it's necessary because
  215. the log() method can't handle a <i>null</i> value as parameter and throws a NullPointerException.
  216. (Of course you can initialize the <i>message</i> with a default string.)</p>
  217. <p>After that we have to modify our buildfile:
  218. <pre class="code">
  219. &lt;target name="use" description="Use the Task" depends="jar"&gt;
  220. &lt;taskdef name="helloworld"
  221. classname="HelloWorld"
  222. classpath="${ant.project.name}.jar"/&gt;
  223. &lt;helloworld <b>message="Hello World"</b>/&gt;
  224. &lt;/target&gt;
  225. </pre>
  226. That's all.</p>
  227. <p>Some background for working with attributes: Ant supports any of these datatypes as
  228. arguments of the set-method:<ul>
  229. <li>elementary data type like <i>int</i>, <i>long</i>, ...</li>
  230. <li>its wrapper classes like <i>java.lang.Integer</i>, <i>java.lang.Long</i>, ...</li>
  231. <li><i>java.lang.String</i></li>
  232. <li>some more classes (e.g. <i>java.io.File</i>; see
  233. <a href="http://ant.apache.org/manual/develop.html#set-magic">Manual
  234. 'Writing Your Own Task' [3]</a>)</li>
  235. </ul>
  236. Before calling the set-method all properties are resolved. So a <tt>&lt;helloworld message="${msg}"/&gt;</tt>
  237. would not set the message string to "${msg}" if there is a property "msg" with a set value.
  238. <a name="NestedText"></a>
  239. <h2>Nested Text</h2>
  240. <p>Maybe you have used the <code>&lt;echo&gt;</code> task in a way like <tt>&lt;echo&gt;Hello World&lt;/echo&gt;</tt>.
  241. For that you have to provide a <tt>public void addText(String text)</tt> method.
  242. <pre class="code">
  243. ...
  244. public class HelloWorld extends Task {
  245. ...
  246. public void addText(String text) {
  247. message = text;
  248. }
  249. ...
  250. }
  251. </pre>
  252. But here properties are <b>not</b> resolved! For resolving properties we have to use
  253. Project's <tt>replaceProperties(String propname) : String</tt> method which takes the
  254. property name as argument and returns its value (or ${propname} if not set).</p>
  255. <a name="NestedElements"></a>
  256. <h2>Nested Elements</h2>
  257. <p>There are several ways for inserting the ability of handling nested elements. See
  258. the <a href="http://ant.apache.org/manual/develop.html#nested-elements">Manual [4]</a> for other.
  259. We use the first way of the three described ways. There are several steps for that:<ol>
  260. <li>We create a class for collecting all the info the nested element should contain.
  261. This class is created by the same rules for attributes and nested elements
  262. as for the task (<code>set&lt;attributename&gt;</code>() 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
  265. and returns it to Ant Core.</li>
  266. <li>The execute() method iterates over the list and evaluates its values.</li>
  267. </ol></p>
  268. <pre class="code">
  269. import java.util.Vector;
  270. import java.util.Iterator;
  271. ...
  272. public void execute() {
  273. if (message!=null) log(message);
  274. for (Iterator it=messages.iterator(); it.hasNext(); ) { <b>// 4</b>
  275. Message msg = (Message)it.next();
  276. log(msg.getMsg());
  277. }
  278. }
  279. Vector messages = new Vector(); <b>// 2</b>
  280. public Message createMessage() { <b>// 3</b>
  281. Message msg = new Message();
  282. messages.add(msg);
  283. return msg;
  284. }
  285. public class Message { <b>// 1</b>
  286. public Message() {}
  287. String msg;
  288. public void setMsg(String msg) { this.msg = msg; }
  289. public String getMsg() { return msg; }
  290. }
  291. ...
  292. </pre>
  293. <p>Then we can use the new nested element. But where is xml-name for that defined?
  294. The mapping XML-name : classname is defined in the factory method:
  295. <tt>public <i>classname</i> create<i>XML-name</i>()</tt>. Therefore we write in
  296. the buildfile
  297. <pre class="code">
  298. &lt;helloworld&gt;
  299. &lt;message msg="Nested Element 1"/&gt;
  300. &lt;message msg="Nested Element 2"/&gt;
  301. &lt;/helloworld&gt;
  302. </pre>
  303. <p>Note that if you choose to use methods 2 or 3, the class that represents the nested
  304. element must be declared as <pre>static</pre></p>
  305. <a name="complex"></a>
  306. <h2>Our task in a little more complex version</h2>
  307. <p>For recapitulation now a little refactored buildfile:
  308. <pre class="code">
  309. &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  310. &lt;project name="MyTask" basedir="." default="use"&gt;
  311. &lt;property name="src.dir" value="src"/&gt;
  312. &lt;property name="classes.dir" value="classes"/&gt;
  313. &lt;target name="clean" description="Delete all generated files"&gt;
  314. &lt;delete dir="${classes.dir}" failonerror="false"/&gt;
  315. &lt;delete file="${ant.project.name}.jar"/&gt;
  316. &lt;/target&gt;
  317. &lt;target name="compile" description="Compiles the Task"&gt;
  318. &lt;mkdir dir="${classes.dir}"/&gt;
  319. &lt;javac srcdir="${src.dir}" destdir="${classes.dir}"/&gt;
  320. &lt;/target&gt;
  321. &lt;target name="jar" description="JARs the Task" depends="compile"&gt;
  322. &lt;jar destfile="${ant.project.name}.jar" basedir="${classes.dir}"/&gt;
  323. &lt;/target&gt;
  324. &lt;target name="use.init"
  325. description="Taskdef the HelloWorld-Task"
  326. depends="jar"&gt;
  327. &lt;taskdef name="helloworld"
  328. classname="HelloWorld"
  329. classpath="${ant.project.name}.jar"/&gt;
  330. &lt;/target&gt;
  331. &lt;target name="use.without"
  332. description="Use without any"
  333. depends="use.init"&gt;
  334. &lt;helloworld/&gt;
  335. &lt;/target&gt;
  336. &lt;target name="use.message"
  337. description="Use with attribute 'message'"
  338. depends="use.init"&gt;
  339. &lt;helloworld message="attribute-text"/&gt;
  340. &lt;/target&gt;
  341. &lt;target name="use.fail"
  342. description="Use with attribute 'fail'"
  343. depends="use.init"&gt;
  344. &lt;helloworld fail="true"/&gt;
  345. &lt;/target&gt;
  346. &lt;target name="use.nestedText"
  347. description="Use with nested text"
  348. depends="use.init"&gt;
  349. &lt;helloworld&gt;nested-text&lt;/helloworld&gt;
  350. &lt;/target&gt;
  351. &lt;target name="use.nestedElement"
  352. description="Use with nested 'message'"
  353. depends="use.init"&gt;
  354. &lt;helloworld&gt;
  355. &lt;message msg="Nested Element 1"/&gt;
  356. &lt;message msg="Nested Element 2"/&gt;
  357. &lt;/helloworld&gt;
  358. &lt;/target&gt;
  359. &lt;target name="use"
  360. description="Try all (w/out use.fail)"
  361. depends="use.without,use.message,use.nestedText,use.nestedElement"
  362. /&gt;
  363. &lt;/project&gt;
  364. </pre>
  365. And the code of the task:
  366. <pre class="code">
  367. import org.apache.tools.ant.Task;
  368. import org.apache.tools.ant.BuildException;
  369. import java.util.Vector;
  370. import java.util.Iterator;
  371. /**
  372. * The task of the tutorial.
  373. * Print a message or let the build fail.
  374. * @since 2003-08-19
  375. */
  376. public class HelloWorld extends Task {
  377. /** The message to print. As attribute. */
  378. String message;
  379. public void setMessage(String msg) {
  380. message = msg;
  381. }
  382. /** Should the build fail? Defaults to <i>false</i>. As attribute. */
  383. boolean fail = false;
  384. public void setFail(boolean b) {
  385. fail = b;
  386. }
  387. /** Support for nested text. */
  388. public void addText(String text) {
  389. message = text;
  390. }
  391. /** Do the work. */
  392. public void execute() {
  393. // handle attribute 'fail'
  394. if (fail) throw new BuildException("Fail requested.");
  395. // handle attribute 'message' and nested text
  396. if (message!=null) log(message);
  397. // handle nested elements
  398. for (Iterator it=messages.iterator(); it.hasNext(); ) {
  399. Message msg = (Message)it.next();
  400. log(msg.getMsg());
  401. }
  402. }
  403. /** Store nested 'message's. */
  404. Vector messages = new Vector();
  405. /** Factory method for creating nested 'message's. */
  406. public Message createMessage() {
  407. Message msg = new Message();
  408. messages.add(msg);
  409. return msg;
  410. }
  411. /** A nested 'message'. */
  412. public class Message {
  413. // Bean constructor
  414. public Message() {}
  415. /** Message to print. */
  416. String msg;
  417. public void setMsg(String msg) { this.msg = msg; }
  418. public String getMsg() { return msg; }
  419. }
  420. }
  421. </pre>
  422. And it works:
  423. <pre class="output">
  424. C:\tmp\anttests\MyFirstTask&gt;ant
  425. Buildfile: build.xml
  426. compile:
  427. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  428. [javac] Compiling 1 source file to C:\tmp\anttests\MyFirstTask\classes
  429. jar:
  430. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  431. use.init:
  432. use.without:
  433. use.message:
  434. [helloworld] attribute-text
  435. use.nestedText:
  436. [helloworld] nested-text
  437. use.nestedElement:
  438. [helloworld]
  439. [helloworld]
  440. [helloworld]
  441. [helloworld]
  442. [helloworld] Nested Element 1
  443. [helloworld] Nested Element 2
  444. use:
  445. BUILD SUCCESSFUL
  446. Total time: 3 seconds
  447. C:\tmp\anttests\MyFirstTask&gt;ant use.fail
  448. Buildfile: build.xml
  449. compile:
  450. jar:
  451. use.init:
  452. use.fail:
  453. BUILD FAILED
  454. C:\tmp\anttests\MyFirstTask\build.xml:36: Fail requested.
  455. Total time: 1 second
  456. C:\tmp\anttests\MyFirstTask&gt;
  457. </pre>
  458. Next step: test ...
  459. <a name="TestingTasks"></a>
  460. <h2>Test the Task</h2>
  461. <p>We have written a test already: the use.* tasks in the buildfile. But its
  462. difficult to test that automatically. Common (and in Ant) used is JUnit for
  463. that. For testing tasks Ant provides a baseclass <tt>org.apache.tools.ant.BuildFileTest</tt>.
  464. This class extends <tt>junit.framework.TestCase</tt> and can therefore be integrated
  465. into the unit tests. But this class provides some for testing tasks useful methods:
  466. initialize Ant, load a buildfile, execute targets,
  467. expecting BuildExceptions with a specified text, expect a special text
  468. in the output log ... </p>
  469. <p>In Ant it is usual that the testcase has the same name as the task with a prepending
  470. <i>Test</i>, therefore we will create a file <i>HelloWorldTest.java</i>. Because we
  471. have a very small project we can put this file into <i>src</i> directory (Ant's own
  472. testclasses are in /src/testcases/...). Because we have already written our tests
  473. for "hand-test" we can use that for automatic tests, too. But there is one little
  474. problem we have to solve: all test supporting classes are not part of the binary
  475. distribution of Ant. So you can build the special jar file from source distro with
  476. target "test-jar" or you can download a nightly build from
  477. <a href="http://gump.covalent.net/jars/latest/ant/ant-testutil.jar">
  478. http://gump.covalent.net/jars/latest/ant/ant-testutil.jar [5]</a>.</p>
  479. <p>For executing the test and creating a report we need the optional tasks <code>&lt;junit&gt;</code>
  480. and <code>&lt;junitreport&gt;</code>. So we add to the buildfile:
  481. <pre class="code">
  482. ...
  483. <font color="#9F9F9F">&lt;project name="MyTask" basedir="." </font>default="test"<font color="#9F9F9F">&gt;</font>
  484. ...
  485. &lt;property name="ant.test.lib" value="ant-testutil.jar"/&gt;
  486. &lt;property name="report.dir" value="report"/&gt;
  487. &lt;property name="junit.out.dir.xml" value="${report.dir}/junit/xml"/&gt;
  488. &lt;property name="junit.out.dir.html" value="${report.dir}/junit/html"/&gt;
  489. &lt;path id="classpath.run"&gt;
  490. &lt;path path="${java.class.path}"/&gt;
  491. &lt;path location="${ant.project.name}.jar"/&gt;
  492. &lt;/path&gt;
  493. &lt;path id="classpath.test"&gt;
  494. &lt;path refid="classpath.run"/&gt;
  495. &lt;path location="${ant.test.lib}"/&gt;
  496. &lt;/path&gt;
  497. &lt;target name="clean" description="Delete all generated files"&gt;
  498. &lt;delete failonerror="false" includeEmptyDirs="true"&gt;
  499. &lt;fileset dir="." includes="${ant.project.name}.jar"/&gt;
  500. &lt;fileset dir="${classes.dir}"/&gt;
  501. &lt;fileset dir="${report.dir}"/&gt;
  502. &lt;/delete&gt;
  503. &lt;/target&gt;
  504. <font color="#9F9F9F">&lt;target name="compile" description="Compiles the Task"&gt;
  505. &lt;mkdir dir="${classes.dir}"/&gt;
  506. &lt;javac srcdir="${src.dir}" destdir="${classes.dir}" </font>classpath="${ant.test.lib}"<font color="#9F9F9F">/&gt;
  507. &lt;/target&gt;</font>
  508. ...
  509. &lt;target name="junit" description="Runs the unit tests" depends="jar"&gt;
  510. &lt;delete dir="${junit.out.dir.xml}"/&gt;
  511. &lt;mkdir dir="${junit.out.dir.xml}"/&gt;
  512. &lt;junit printsummary="yes" haltonfailure="no"&gt;
  513. &lt;classpath refid="classpath.test"/&gt;
  514. &lt;formatter type="xml"/&gt;
  515. &lt;batchtest fork="yes" todir="${junit.out.dir.xml}"&gt;
  516. &lt;fileset dir="${src.dir}" includes="**/*Test.java"/&gt;
  517. &lt;/batchtest&gt;
  518. &lt;/junit&gt;
  519. &lt;/target&gt;
  520. &lt;target name="junitreport" description="Create a report for the rest result"&gt;
  521. &lt;mkdir dir="${junit.out.dir.html}"/&gt;
  522. &lt;junitreport todir="${junit.out.dir.html}"&gt;
  523. &lt;fileset dir="${junit.out.dir.xml}"&gt;
  524. &lt;include name="*.xml"/&gt;
  525. &lt;/fileset&gt;
  526. &lt;report format="frames" todir="${junit.out.dir.html}"/&gt;
  527. &lt;/junitreport&gt;
  528. &lt;/target&gt;
  529. &lt;target name="test"
  530. depends="junit,junitreport"
  531. description="Runs unit tests and creates a report"
  532. /&gt;
  533. ...
  534. </pre></p>
  535. <p>Back to the <i>src/HelloWorldTest.java</i>. We create a class extending
  536. <i>BuildFileTest</i> with String-constructor (JUnit-standard), a <i>setUp()</i>
  537. method initializing Ant and for each testcase (targets use.*) a <i>testXX()</i>
  538. method invoking that target.
  539. <pre class="code">
  540. import org.apache.tools.ant.BuildFileTest;
  541. public class HelloWorldTest extends BuildFileTest {
  542. public HelloWorldTest(String s) {
  543. super(s);
  544. }
  545. public void setUp() {
  546. // initialize Ant
  547. configureProject("build.xml");
  548. }
  549. public void testWithout() {
  550. executeTarget("use.without");
  551. assertEquals("Message was logged but should not.", getLog(), "");
  552. }
  553. public void testMessage() {
  554. // execute target 'use.nestedText' and expect a message
  555. // 'attribute-text' in the log
  556. expectLog("use.message", "attribute-text");
  557. }
  558. public void testFail() {
  559. // execute target 'use.fail' and expect a BuildException
  560. // with text 'Fail requested.'
  561. expectBuildException("use.fail", "Fail requested.");
  562. }
  563. public void testNestedText() {
  564. expectLog("use.nestedText", "nested-text");
  565. }
  566. public void testNestedElement() {
  567. executeTarget("use.nestedElement");
  568. assertLogContaining("Nested Element 1");
  569. assertLogContaining("Nested Element 2");
  570. }
  571. }
  572. </pre></p>
  573. <p>When starting <tt>ant</tt> we'll get a short message to STDOUT and
  574. a nice HTML-report.
  575. <pre class="output">
  576. C:\tmp\anttests\MyFirstTask&gt;ant
  577. Buildfile: build.xml
  578. compile:
  579. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  580. [javac] Compiling 2 source files to C:\tmp\anttests\MyFirstTask\classes
  581. jar:
  582. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  583. junit:
  584. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\report\junit\xml
  585. [junit] Running HelloWorldTest
  586. [junit] Tests run: 5, Failures: 0, Errors: 0, Time elapsed: 2,334 sec
  587. junitreport:
  588. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\report\junit\html
  589. [junitreport] Using Xalan version: Xalan Java 2.4.1
  590. [junitreport] Transform time: 661ms
  591. test:
  592. BUILD SUCCESSFUL
  593. Total time: 7 seconds
  594. C:\tmp\anttests\MyFirstTask&gt;
  595. </pre></p>
  596. <a name="resources"></a>
  597. <h2>Resources</h2>
  598. <p>This tutorial and its resources are available via
  599. <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=22570">BugZilla [6]</a>.
  600. The ZIP provided there contains<ul>
  601. <li>this tutorial</li>
  602. <li>the buildfile (last version)</li>
  603. <li>the source of the task (last version)</li>
  604. <li>the source of the unit test (last version)</li>
  605. <li>the ant-testutil.jar (nightly build of 2003-08-18)</li>
  606. <li>generated classes</li>
  607. <li>generated jar</li>
  608. <li>generated reports</li>
  609. </ul>
  610. The last sources and the buildfile are also available
  611. <a href="tutorial-writing-tasks-src.zip">here [7]</a> inside the manual.
  612. </p>
  613. Used Links:<br>
  614. &nbsp;&nbsp;[1] <a href="http://ant.apache.org/manual/using.html#built-in-props">http://ant.apache.org/manual/using.html#built-in-props</a><br>
  615. &nbsp;&nbsp;[2] <a href="http://ant.apache.org/manual/CoreTasks/taskdef.html">http://ant.apache.org/manual/CoreTasks/taskdef.html</a><br>
  616. &nbsp;&nbsp;[3] <a href="http://ant.apache.org/manual/develop.html#set-magic">http://ant.apache.org/manual/develop.html#set-magic</a><br>
  617. &nbsp;&nbsp;[4] <a href="http://ant.apache.org/manual/develop.html#nested-elements">http://ant.apache.org/manual/develop.html#nested-elements</a><br>
  618. &nbsp;&nbsp;[5] <a href="http://gump.covalent.net/jars/latest/ant/ant-testutil.jar">http://gump.covalent.net/jars/latest/ant/ant-testutil.jar</a><br>
  619. &nbsp;&nbsp;[6] <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=22570">http://issues.apache.org/bugzilla/show_bug.cgi?id=22570</a><br>
  620. &nbsp;&nbsp;[7] <a href="tutorial-writing-tasks-src.zip">tutorial-writing-tasks-src.zip</a><br>
  621. </body>
  622. </html>