NetBeans7.0でjmockitを使ってテスト1
id:j5ik2oさんの以下の記事を読んで、jmockitを使ってみました。
[JMockit] - じゅんいち☆かとうの技術日誌
- NetBeans7.0でまずmaven projectを作成。
Junitのバージョンを4.5以上に変更。pom.xmlにjmockitを追加。
<dependencies> <dependency> <groupId>com.googlecode.jmockit</groupId> <artifactId>jmockit</artifactId> <version>0.999.12</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies>
- テスト対象のクラス
public class HelloWorld { public String sayHello(){ final String language = Locale.getDefault().getLanguage(); if (language.equals(Locale.JAPANESE.getLanguage())){ if (isAfternoon()) { return "こんばんは"; } else { return "こんにちは"; } } else if (language.equals(Locale.ENGLISH.getLanguage())){ if (isAfternoon()) { return "Good Aftermoon"; } else { return "Good Morning"; } } return "?"; } private boolean isAfternoon(){ Date date = new Date(System.currentTimeMillis()); // ここをjmockitを使用してモック Formatter formatter = new Formatter(); String hour = formatter.format("%tH", date).toString(); if (Long.parseLong(hour) > 17) { return true; } else { return false; } } }
テスト対象として、System.currentTimeMillis()メソッドの値により処理を分岐。
で、テストクラスでSystem.currentTimeMillis()メソッドの戻り値をjmockitを使って設定。
- テストクラス
public class HelloWorldTest { @mockit.Mocked final System system = null; @Test public void testSayHello1InJapanese() { new NonStrictExpectations(){ { System.currentTimeMillis(); // ここでjmockitを使って現在時刻を設定 result=1000 * 60 * 60 * 1L; } }; HelloWorld instance = new HelloWorld(); String expResult = "こんにちは"; String result = instance.sayHello(); assertEquals(expResult, result); new NonStrictExpectations(){ { System.currentTimeMillis(); result=1000 * 60 * 60 * 10L; // ここでもjmockitを使って現在時刻を設定 } }; expResult = "こんばんは"; result = instance.sayHello(); assertEquals(expResult, result); } @Test public void testSayHelloInEnglish(){ new NonStrictExpectations(){ { System.currentTimeMillis(); result=1000 * 60 * 60 * 1L; } }; Locale.setDefault(Locale.ENGLISH); HelloWorld instance = new HelloWorld(); String expResult = "Good Morning"; String result = instance.sayHello(); assertEquals(expResult, result); new NonStrictExpectations(){ { System.currentTimeMillis(); result=1000 * 60 * 60 * 10L; } }; expResult = "Good Aftermoon"; result = instance.sayHello(); assertEquals(expResult, result); } }
- テストが成功。
とりあえず上記のクラスを、gitHubにアップ。
tomoTaka01/singletonTestProject: maven project using junit and jmockit
まだまだ説明不足、書き方がいけてない、などありますが、
少しずつこれからブログを書いていく!