JUnit4 でどうしてもアノテーションなしでテストしたい場合
ここでは、Maven や Gradle なしで 素のJava で、アノテーションなしで Junit を使うコードを書きます。
Junit4 の内部構造を知る上で、ライブラリの使い方が載っていなかったので、記事にしました(コメントを読めば分かるんですが・・・)。
まずは、Junit4 の src/main/java の下の junit
フォルダをプロジェクトの配下に置きます。
そして、テストを行いたいファイルで まず TestCase を継承したテストクラスを作成します。
import junit.framework.Assert;
import junit.framework.TestCase;
import junit.framework.TestResult;
public class Hoge {
public static class HogeTest extends TestCase {
protected double someValue1;
protected double someValue2;
protected void setup() {
someValue1 = 1.0;
someValue2 = 2.0;
}
}
}
ここに、テストケースを検証するメソッドを追加します。
protected void setup() {
someValue1 = 1.0;
someValue2 = 2.0;
}
public void testAdd() {
double result = someValue1 + someValue2;
Assert.assertTrue(result == 3.0);
}
Assert の種類は、Assert.java を参照にしてみて下さい。
そして、このテストを動かすコードを書きます。
public void testAdd() {
double result = someValue1 + someValue2;
Assert.assertTrue(result == 3.0);
}
public void main(String[] args) {
TestCase test = new MathTest() {
public void runTest() {
setup();
testAdd();
}
}
TestResult testResult = test.run();
/* Test Result */
int totalTest = testResult.runCount();
int failureCount = testResult.failureCount();
int errorCount = testResult.errorCount();
int successCount = totalTest - failureCount - errorCount;
System.out.println("Success Count : " + successCount);
System.out.println("Failure Count : " + failureCount);
System.out.println("Error Count : " + errorCount);
}
ここまでで、テストの結果が表示できます。
また、TestResult.java に以下のような toString()
を追加することで System.out.println(testResult);
で結果を表示することもできます。
@Override
public String toString() {
int fSuccesses = this.fRunTests - this.fFailures.size() - this.fErrors.size();
return "Total " + this.fRunTests + " tests run.\n-----\n"
+ "Success " + fSuccesses + " tests\n"
+ "Failures " + this.fFailures.size() + " tests\n"
+ "Errors " + this.fErrors.size() + " tests";
}
以下、全コード
import junit.framework.Assert;
import junit.framework.TestCase;
import junit.framework.TestResult;
public class Sample {
public static class MathTest extends TestCase {
protected double fValue1;
protected double fValue2;
protected void setup() {
fValue1 = 2.0;
fValue2 = 3.0;
}
public void testAdd() {
double result = fValue1 + fValue2;
Assert.assertTrue(result == 5.0);
}
}
public static void main(String[] args) {
TestCase test = new MathTest() {
public void runTest() {
setup();
testAdd();
}
};
TestResult testResult = test.run();
System.out.println(testResult);
}
}