JUnit4 の @Test でも簡単にパフォーマンステストが出来た!!!

今まで、パフォーマンスに注意しなきゃいけないところは
テストに

StopWatch stopWatch = new StopWatch();
List<Long> times = new ArrayList<Long>();
for(int i = 0 ; i < 100 ; i++){
	stopWatch.reset();
	stopWatch.start();
	
	foo.bar(); //計測する処理

	stopWatch.stop();
	times.add(stopWatch.getTime());
}
BigDecimal sum = new BigDecimal(0L);
for(Long i : times){
	sum = sum.add(new BigDecimal(i));
}
Long average = sum.divide(new BigDecimal(times.size())).longValue();
System.out.println("初回 : " + times.get(0) + " ms.");
System.out.println("平均 : " + average + " ms.");
assertThat(times.get(0), is(lessThan(30000L)));
assertThat(average, is(lessThan(20000L)));

みたいに書いてた。
んで、毎回、lessThan が保管されなくて、hamcrest のライブラリ入れなきゃいけなくて
ウガーとか思ってたんだけど、簡単なパフォーマンスの監視だったら、
JUnit4 の @Test アノテーションに timeout 指定出来た><

@Test(timeout=20000)
public void barの処理が正常に実行される() throws Exception {
    foo.bar(); //計測する処理
    assertThat(foo.getHoge(), is("hoge"));
}

http://kentbeck.github.com/junit/javadoc/latest/org/junit/Test.html

知らなかったわーーー><

追記

kompiro @RuleのTimeoutを設定すると、クラス全体で監視できますよ。

http://b.hatena.ne.jp/kompiro/20110328#bookmark-35750778

ブクマで id:kompiro に教えてもらった!!
http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/Timeout.html

 public static class HasGlobalTimeout {
        public static String log;
 
        @Rule
        public MethodRule globalTimeout= new Timeout(20);
 
        @Test
        public void testInfiniteLoop1() {
                log+= "ran1";
                for (;;) {
                }
        }
 
        @Test
        public void testInfiniteLoop2() {
                log+= "ran2";
                for (;;) {
                }
        }
 }

一瞬、「クラス単位で出来てなんか意味あるのかなぁ?」と思ったけど、
スローテスト問題の切り分けとか、無限ループに嵌った時にもテストが終わるとかで使い道ありそう!!