【JUnit】JUnit ~ 基本編 ~

アノテーションについて

 * 以下の関連記事を参照
https://blogs.yahoo.co.jp/dk521123/35267660.html

■ 比較する

* (知ってる限りだと)以下の2つの方法がある。
【1】 assertEquals() を使って比較する(以下のサンプル「testEx01()」を参照)
 => 「assertEquals([期待値], [確認する値]);」

【2】 assertThat() を使って比較する(以下のサンプル「testEx02()」を参照)
 => 「assertThat([確認する値], is([期待値]));」
 => is()には、「import static org.hamcrest.CoreMatchers.*;」が必要
 => 以下の関連記事でも使用している
https://blogs.yahoo.co.jp/dk521123/35127759.html

サンプル

テスト対象
public class HelloWorld {
  public static String sayHello() {
    return "Hello World!";
  }
}
テストコード
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

public class HelloWorldTest {
  @Test
  public void testEx01() {
    assertEquals("Hello World!", HelloWorld.sayHello());
  }
  
  @Test
  public void testEx02() {
    assertThat(HelloWorld.sayHello(), is("Hello World!"));
  }

  // 出力結果
  // org.junit.ComparisonFailure: expected:<Hello World[]> but was:<Hello World[!]>
  @Test
  public void testEx01NG() {
    assertEquals("Hello World", HelloWorld.sayHello());
  }

  // 出力結果
  // Expected: is "Hello World"
  //   but: was "Hello World!"
  @Test
  public void testEx02NG() {
    assertThat(HelloWorld.sayHello(), is("Hello World"));
  }
}

参考文献

assertThat()
https://qiita.com/opengl-8080/items/e57dab6e1fa5940850a3

■ 例外に関する単体試験

  * (知ってる限りだと)以下の3つの方法がある。

【1】 try-catch と fail() で試験する

 => fail()は、実行したら無条件でエラーになる
サンプル
// こんな感じで実装する
@Test
public void testThrowTestException() {
   try {
        throwTestException(null);
        fail("Error");
   } catch (TestException e) {
        System.out.println("Success!" ); // こっちに入ったら試験成功
        return;
   } catch (Exception ex) {
        fail("Error" + ex.getMessage());
   }
}

【2】 @Testアノテーションの expected 属性を使って記述する

 => ただし、JUnit4以降である必要がある
サンプル
@Test(expected=TestException.class)
public void testThrowTestException() throws Exception {
    throwTestException(null);
}

【3】 @RuleアノテーションとExpectedException を利用する

 => 例外のメッセージのテストもできる
サンプル
@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testThrowTestException() throws Exception {
    exception.expect(TestException.class);
    exception.expectMessage("This is an exception test!!"); // 例外のメッセージのテストもできる
    throwTestException(null);
}

■ テストスイートについて

テストスイートとは?

 * 多数のテストケースを束ねたもの
  => JUnitには、テストケースクラスを作成できる

Eclipse上でのテストケースクラスの作成

[1] テストの対象のプロジェクトを右クリックし、
    [New]-[Other]-[Java]-[JUnit]-[JUnit Test Suite]で「Next」ボタン押下
[2] 「Package」欄に任意のパッケージ名を入力し、「Finish」ボタン押下
 => 自動的にテストケースクラスを作成してくれる

サンプル

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ DemoTest.class })
public class AllTests {
}