解答例 – 7.基本的なタスク
(実習課題)
- 以下のプログラムとテストプログラムに対し、コンパイルから単体テスト実行までを行うビルドファイルを作成し、実行結果を確認して下さい。
- テスト結果のフォーマットを変えて違いを確認して下さい。
- テストが通るようにプログラムを変更し、ビルドファイルにプログラムを実行するタスクを追加して下さい。
解答例 1
ファイル構造
./ build.xml ├lib/junit.jar ├src/main/java/Calc.java └src/main/test/CalcTest.java
<?xml version="1.0" encoding="UTF-8" ?>
<project name="Chapter7Exercise" default="test" basedir=".">
<description>7章の演習課題:解答例</description>
<property name="src" location="src/main/java"/>
<property name="lib" location="lib"/>
<property name="test" location="src/test/java"/>
<property name="out" location="out"/>
<path id="classpath">
<pathelement location="${out}"/>
</path>
<path id="classpath-test">
<pathelement location="${lib}/junit.jar"/>
</path>
<target name="compile" description="テスト対象をコンパイル">
<mkdir dir="${out}"/>
<javac srcdir="${src}" destdir="${out}" includeantruntime="false" debug="true"/>
</target>
<target name="compile-test" description="テストプログラムをコンパイル">
<javac srcdir="${test}" destdir="${out}"
classpathref="classpath-test" includeantruntime="false" debug="true"/>
</target>
<target name="test" depends="compile, compile-test" description="テストを実行">
<junit printsummary="yes">
<classpath>
<path refid="classpath"/>
<path refid="classpath-test"/>
</classpath>
<formatter type="xml" />
<batchtest todir="${out}">
<fileset dir="${test}" includes="**/*Test.java" />
</batchtest>
</junit>
</target>
<target name="delete" description="コンパイル結果、テスト結果を削除">
<delete dir="${out}" />
</target>
</project>
実行結果
ファイル作成、実行後、out/TEST-CalcTest.xml を確認して下さい。
解答例 2
省略
解答例 3
1. [Calc.xml] のapplyメソッドを以下の様に書き換える
public int apply(String csv) {
int[] numbers = parse(csv);
int result = numbers[0];
for (int i = 1; i < numbers.length; i++) {
int n = numbers[i];
if (mode == Mode.Summation) {
result += n;
} else if (mode == Mode.Product) {
result *= n;
}
}
return result;
}
2. [build.xml]に以下を付け加える
<target name="sum"
description="整数の総和を求める(例:ant sum -Dnumbers="1,2,4")">
<antcall target="-run">
<param name="mode" value="Summation"/>
</antcall>
</target>
<target name="prod"
description="整数の総乗を求める(例:ant prod -Dnumbers="1,2,4")">
<antcall target="-run">
<param name="mode" value="Product"/>
</antcall>
</target>
<target name="-run" depends="compile"
description="sum,prodから呼ばれてプログラムを実行する">
<java classname="Calc" classpathref="classpath" fork="true">
<arg value="${mode}"/>
<arg value="${numbers}"/>
</java>
</target>

