NetBeans7.0でjunitを使ってテストのサンプル
まずjmockitをここからdownload(今日の時点の最新バージョン0.999.7)
次にJunitをここから(とりあえず4.10のbasic.jar)を選択
最後にhamcrestをここから(とりあえず1.2のcore)
jmockit.jar、Jnit-4.10.jar、hamcrest-core-1.2.jarの順でクラスパスに追加。
NetBeans7.0を使用するので、ライブラリーに追加。
- テスト対象クラス
public class TargetClass { private List<PersonInfo> personInfos = new ArrayList<PersonInfo>(); // <--★1 private void doSomething(String name) { String sql1 = "selet * from person where name like " + name; // <--★2 List<Person> persons = DataUtils.getPersons(sql1); // <--★3ここをモック for (Person person : persons) { PersonInfo personInfo = new PersonInfo(); personInfo.setName(name); switch (person.getType()) { case STUDENT: // <--★パターン1 personInfo.setType(Type.STUDENT); personInfo.setTypeName("school"); personInfo.setAge(20); break; case OFFICEWORKER: // <--★パターン2 personInfo.setType(Type.OFFICEWORKER); personInfo.setTypeName("company"); personInfo.setAge(25); break; } personInfos.add(personInfo); } } }
- テストクラス
public class TargetClassTest { private String sql1 = "selet * from person where name like name1";// <--★2 @Mocked final DataUtils dataUtils = null; // <--★3モック対象 /** * Test of doSomething method, of class TargetClass. */ @Test public void testDoSomething() { PersonInfo personInfo = new PersonInfo(); final List<Person> exp = new ArrayList<Person>(); Person person1 = new Person(); person1.setType(Type.STUDENT); exp.add(person1); // <--パターン1用 Person person2 = new Person(); person2.setType(Type.OFFICEWORKER); exp.add(person2); // <--パターン2用 new Expectations(){{ DataUtils.getPersons(sql1); // <--★3モック対象のメソッド指定 result = exp; // <--★3モック値を設定 }}; List<PersonInfo> personInfos = new ArrayList<PersonInfo>(); TargetClass target = new TargetClass(); Deencapsulation.setField(target, personInfos);// <--★1テスト時に必要な変数を設定 String result = Deencapsulation.invoke(target, "doSomething", "name1"); // <--テスト対象メソッドの実行 // ★パターン1の実行結果を検証 assertThat(personInfos.get(0).getTypeName(), is("school")); assertThat(personInfos.get(0).getType(), is(Type.STUDENT)); assertThat(personInfos.get(0).getAge(), is(20)); // ★パターン2の実行結果を検証 assertThat(personInfos.get(1).getTypeName(), is("company")); assertThat(personInfos.get(1).getType(), is(Type.OFFICEWORKER)); assertThat(personInfos.get(1).getAge(), is(25)); } }
jmocikを使うと、★1のprivate変数が設定できる。
★3のstaticメソッドもモック可能(staticメソッドのクラスはfinal指定でnullを設定しておく)
ここではまったのが★3のモック対象のメソッドの引数の値(ここではSQL文)が実行時とモック時で違っているとエラーになること。
参考までに全ソースはgithubのTestSampleにアップ。