Skip to content

Instantly share code, notes, and snippets.

@ironchefpython
Created April 3, 2012 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ironchefpython/2292944 to your computer and use it in GitHub Desktop.
Save ironchefpython/2292944 to your computer and use it in GitHub Desktop.
Rhino Test

###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);
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment