How to test "Timer code" in a GWTTestCase?

Sebastien Diot

I am writing code using GWT, and I have created a java.util.Timer emulation, which I could like to test. In Java, I would create a Timer, fire a task on it, wait until the task was executed, and then return from successfully the unit test method (or fail, after some timeout expired).

I don't know much about JavaScript (which is why I use GWT), but I have seen examples using the JavaScript "native" timer functions setTimeout()/setInterval(), where the handler/callback, used a flag to make sure it was not called "while executing". In other words, some example said/implied that it is possible that while the callback/handler takes long to execute, it then gets called again, as the interval ran out once more. And so the examples used some flag, which the callback checked to make sure it does nothing if the last call to it did not end yet.

This made me assume that I can use setInterval() (indirectly, through GWT), to get some callback to be executed while my code is waiting. Since there is no "sleep" in JavaScript, I used a "busy loop" instead, but the callback never got executed.

So, is it that my assumption about "async callback" is wrong (sometimes, always?), or that the GWT Timer class (or htmlunit itself) somehow prevents this behavior (idk how the GWT Timer is implemented internally)?

And more importantly, how can I then test my java.util.Timer emulation in a GWTTestCase, if any TimerTask I create within a test method call simply won't execute until the test method call returned?

In the "real application", there will be a "game loop", and the timer tasks are free to run between the game loop cycles.

GWT code is something like:

public class TimerTest extends GWTTestCase {
    public void testScheduleLong() {
        final Timer timer = new Timer("test");
        final boolean[] marker = new boolean[] { false };
        new com.google.gwt.user.client.Timer() {
            @Override
            public void run() {
                marker[0] = true;
            }
        }.schedule(10);

        assertFalse("marker[0]", marker[0]);
        double value = Long.MAX_VALUE;
        // Waste time, to see if marker changes
        final long start = System.currentTimeMillis();
        while (!marker[0] && (System.currentTimeMillis() - start < 1000)) {
            value = Math.sqrt(value);
            if (value > 1) {
                value = Long.MAX_VALUE;
            }
        }
        assertTrue("marker[0]", marker[0]);
    }
}
Sebastien Diot

Thanks to a comment for @ColinAlworth, which basically answered this question in a comment on another question, I found there is support for testing timers: GWTTestCase.delayTestFinish(int timeoutMillis) + finishTest()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related