Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

JUnit | JUnit4による基本的なケース作成

パンくず

Java
JUnit
JUnit4による基本的なケース作成

概要

JUnit4による基本的なケース作成について

テストケースのルール

・テストクラスはテスト対象のクラス名+Test
・テストメソッドは@Testアノテーションを付加する

JUnit3以前ではテストクラスはTestCaseを継承し、
テストメソッドはtestでメソッド名を開始する必要がありましたが
JUnit4からはこのルールは不要です。

JUnit4による基本的なテストケース

テストコードの実行は主に以下の流れになります。
・事前条件の設定
・対象コードの実行
・実行結果の検証

実行結果の検証はassertThatメソッドで行います。

/*
* actualは実行結果
* expectedは期待値。isはMatcherのメソッドです。
* JUnit3までは各種データ型ごとのassertEqualsなどが用意されていましたが
* JUnit4ではassertThatのみを利用します。
* 旧assert系メソッドも後方互換のために利用可能
*/
assertThat(actual, is(expected));

JUnit4による例外のテストケース

例外のテストを行う場合はアノテーションを利用します。

@Test(expected = 例外クラス名.class)

ただし、例外に設定されたメッセージ等詳細内容を検証する場合は
try-catchとassertThartを利用することになります。

サンプルコード

プロダクトコード

public class PrintHoge {
  public String printLowerCase(String hoge) throws Exception {
    if (hoge.equals("hoo")) {
      throw new Exception("hoo");
    }
    return "hoge|" + hoge.toLowerCase();
  }
}

テストコード

/**
 *
 */
package gr.java_conf.tb.java_sample_code.junit;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PrintHogeTest {

  @Before
  public void setUp() throws Exception {
  }

  @After
  public void tearDown() throws Exception {
  }

  @Test
  public void testPrintLowerCase_正常値() throws Exception {
    PrintHoge printHoge = new PrintHoge();
    String hoge = printHoge.printLowerCase("Hoge");
    assertThat(hoge, is("hoge|hoge"));
  }
  @Test(expected = NullPointerException.class)
  public void testPrintLowerCase_Null指定() throws Exception {
    PrintHoge printHoge = new PrintHoge();
    printHoge.printLowerCase(null);
  }
  @Test
  public void testPrintLowerCase_hoo指定() {
    PrintHoge printHoge = new PrintHoge();
    try {
      printHoge.printLowerCase("hoo");
      fail();
    } catch (Exception e) {
      assertThat(e.getMessage(), is("hoo"));
    }
  }

}