15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

junitでprivateメソッドのテストをする話

15
Last updated at Posted at 2014-12-25

ここ最近、クラスファイルを新規で作ったり編集したらテストをちゃんと書こう!的なのを実践中なのだけれど、プライベートメソッドって他所から呼べないからプライベートなわけで。。。

まぁ、書かないわけにもいかないし、結果調べて書けたので忘れないようにメモっておく。

とりあえずやってみよう


対象クラスは適当に(残念な感じに)書いてみた。

public class MyClass {
    private String getGreeting(String name) {
        return "hello! " + name;
    }
}

以下がテストクラス。

import static org.junit.Assert.assertEquals;
import java.lang.reflect.Method;
import mockit.Tested;
import org.junit.Test;

public class MyClassTest {
    @Tested
    private MyClass sut;

    @Test
    public void test() throws Exception {
        Method method = MyClass.class.getDeclaredMethod("getGreeting", String.class);
        method.setAccessible(true);
        assertEquals((String) method.invoke(sut, "bob"), "hello! bob");
    }
}

なにやってんの?


Method method = MyClass.class.getDeclaredMethod("getGreeting", String.class);

privateメソッドちゃんを探しだしてMethodオブジェクトを作ってくれている模様。
getDeclaredMethod(メソッド名(, 第一引数の型, 第二引数の型…)
※ 引数がないメソッドの場合はメソッド名だけでおk

method.setAccessible(true);

privateメソッドにアクセス可能になるおまじない。

(String) method.invoke(sut, "bob")

privateメソッドの呼び出し。
invoke(インスタンス(, 第一引数, 第二引数...))
今回はメソッドの戻り値が文字列なのでStringにキャストしたった!

これで


無事にprivateメソッドもテスト書けるようになったのです。
使い方覚えてしまえば難しくないんだろうけど、結局毎度調べてるという…笑

15
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?