###MockEngine.java
package org.terasology.rhinodemo;
import org.mozilla.javascript.*;
import org.w3c.dom.events.EventTarget;
public class MockEngine {
Context cx;
Scriptable scope;
public MockEngine(Game game) {
// Create a javascript context, and initialize the basic objects
cx = Context.enter();
scope = cx.initStandardObjects();
// add a console.log command
ScriptableObject.putProperty(scope, "console", Context.javaToJS(new Console(), scope));
// make the game instance available for scripting.
ScriptableObject.putProperty(scope, "game", Context.javaToJS(game, scope));
}
public void exec(String s) {
cx.evaluateString(scope, s, "<cmd>", 1, null);
}
public class Console {
public void log(String s) {
System.err.println("js> " + s);
}
}
public interface Game extends EventTarget { }
}
###EventTest.java
package org.terasology.rhinodemo;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.terasology.rhinodemo.MockEngine.Game;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.MouseEvent;
import static org.mockito.Mockito.*;
public class EventTest {
@Test
public void mockTest() {
Game game = mock(Game.class);
MockEngine r = new MockEngine(game);
r.exec("game.addEventListener('test', function(evt) { console.log(evt.type) }, false)");
ArgumentCaptor<EventListener> argument = ArgumentCaptor.forClass(EventListener.class);
verify(game).addEventListener(anyString(), argument.capture(), eq(false));
MouseEvent uiEvent= mock(MouseEvent.class);
when(uiEvent.getType()).thenReturn("mouseevent");
argument.getValue().handleEvent(uiEvent);
}
}