here で説明されているように、gwt-test-utils フレームワークを使用して単体テストを作成しました。テストされたクラスは内部的にcom.google.gwt.user.client.Timer
(Java のデフォルトのタイマーではなく) を使用します。
ただし、Timer インスタンスは、スケジュールされるとすぐに起動するため、テストされた場合にのみ正しく動作しません。
このテストを実行すると
public class TimerTest extends GwtTest {
@Override
public String getModuleName() {
return "com.whatevs";
}
@Test
public void testTimer() {
final int[] counter = { 0 };
com.google.gwt.user.client.Timer t = new Timer() {
@Override
public void run() {
Log.info("firing timer");
counter[0]++; // just increase the counter
}
};
Log.info("scheduling timer");
t.schedule(1000000); // this should return immediately
Log.info("scheduling returns");
assertEquals(0, counter[0]); // the counter shouldn't yet be incremented
}
}
失敗する
testTimer(com.whatevs.TimerTest): expected:<0> but was:<1>
そしてデバッグ出力
22:37:44,075 INFO gwt-log:81 - scheduling timer
22:37:44,075 INFO gwt-log:81 - firing timer
22:37:44,075 INFO gwt-log:81 - scheduling returns
テストは最初に JavaScript にコンパイルされることなく、JUnit テストとして実行されることに注意してください。
私は何か間違ったことをしていますか、それともバグに遭遇しただけですか? そのようなクラスをテストする他の方法はありますか?
更新:
上記の例で scheduleRepeating を呼び出すか、run メソッド内でスケジュールを使用してタイマーを再スケジュールすると、呼び出し元に制御を返す前にタイマーが正確に 5 回起動することがわかりました。
gwt-test-utils でバグ レポートを開いたところです。