Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

Java | EasyMockで単体テストをMockする

概要

EasyMockで単体テストをMockする

詳細

EasyMockで単体テストをMockします。

導入手順

・下記URLからjarをダウンロード
http://sourceforge.net/projects/cglib/files/
http://sourceforge.net/projects/easymock/files/EasyMock/3.1/easymock-3.1.zip/download
・対象プロジェクトのビルドバスにjarを追加

サンプルコード

package easymock;

public class SampleEasyMock {
  public String ret = "";
  public Hage hage = null;

  public void hoge(String message) throws IllegalArgumentException {
    ret = hage.hage(message);
  }

  public class Hage {
    public String hage(String message) throws IllegalArgumentException {
      if (message == null) {
        throw new IllegalArgumentException();
      }
      return "hage" + message;
    }
  }

}

テストコード

package easymock;

import static org.easymock.EasyMock.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

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

public class SampleEasyMockTest {

  @Before
  public void setup() {
    reset();
  }

  // 通常のモック
  @Test
  public void testPattern1() {
    SampleEasyMock.Hage hage = createMock(SampleEasyMock.Hage.class);
    expect(hage.hage("-hoge")).andReturn("not hoge");
    replay(hage);
    SampleEasyMock easyMock = new SampleEasyMock();
    easyMock.hage = hage;

    easyMock.hoge("-hoge");
    assertThat(easyMock.ret, is("not hoge"));
  }

  // 例外のモック
  @Test
  public void testPattern2() {
    SampleEasyMock.Hage hage = createMock(SampleEasyMock.Hage.class);
    expect(hage.hage("-hoge")).andThrow(new IllegalArgumentException());
    replay(hage);

    SampleEasyMock easyMock = new SampleEasyMock();
    easyMock.hage = hage;
    try {
      easyMock.hoge("-hoge");
    } catch (IllegalArgumentException e) {
      assertThat(e.getClass().getSimpleName(), is(IllegalArgumentException.class.getSimpleName()));
    }
  }

  // voidのモック
  @Test
  public void testPattern3() {
    SampleEasyMock hoge = createMock(SampleEasyMock.class);
    hoge.hoge("-hoge");
    expectLastCall().andThrow(new IllegalArgumentException());
    replay(hoge);

    try {
      hoge.hoge("-hoge");
    } catch (IllegalArgumentException e) {
      assertThat(e.getClass().getSimpleName(), is(IllegalArgumentException.class.getSimpleName()));
    }
  }
}