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

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