Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
The base source code for FxJsJUnit.
<!DOCTYPE HTML>
<html lang="ja">
<head>
<title>test page</title>
</head>
<body>
<h1 id="title">title</h1>
<p id="test">test</p>
<p id="loaded"></p>
<script lang="javascript" type="text/javascript" src="js/test.js"></script>
</body>
</html>
package org.mikeneck.jfx;
import javafx.application.Application;
import org.junit.*;
import org.mikeneck.jfx.server.MockWebServer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author: mike
* @since: 12/03/07
*/
public class JsJUnit {
private TestBrowser testBrowser;
private ExecutorService executorService;
private static MockWebServer server;
@BeforeClass
public static void setUpWebServer() throws Exception {
server = new MockWebServer();
server.start();
}
@AfterClass
public static void tearDownServer () throws Exception {
server.stop();
}
@Test
public void doNumberTest() throws InterruptedException {
Integer value = testBrowser.runScript("numberTest(1)", Integer.class);
assertThat(value, is(2));
}
@Test
public void doStringTest() throws InterruptedException {
String value = testBrowser.runScript("stringTest('test')", String.class);
assertThat(value, is("test_test"));
}
@Before
public void setUp () throws InterruptedException {
executorService = Executors.newFixedThreadPool(1);
executorService.submit(
new Runnable() {
@Override
public void run() {
Application.launch(TestBrowser.class, server.getUrl());
}
}
);
while (TestBrowser.isReady() == false) {
Thread.sleep(100);
}
testBrowser = TestBrowser.getInstance();
}
@After
public void tearDown () {
executorService.shutdown();
testBrowser.shutdown();
}
}
package org.mikeneck.jfx.server;
import org.eclipse.jetty.server.Server;
import org.mikeneck.jfx.handler.RequestHandler;
import java.net.InetSocketAddress;
/**
* @author: mike
* @since: 12/03/07
*/
public class MockWebServer {
private Server server;
private String hostName;
private int port;
public MockWebServer() {
createServer("localhost", 3080);
}
public MockWebServer(String hostName, int port) {
createServer(hostName, port);
}
private void createServer(String hostName, int port) {
this.hostName = hostName;
this.port = port;
InetSocketAddress address = new InetSocketAddress(hostName, port);
server = new Server(address);
setUpServer();
}
private void setUpServer () {
RequestHandler handler = new RequestHandler(server);
server.setHandler(handler);
}
public String getHostName() {
return hostName;
}
public int getPort() {
return port;
}
public String getUrl () {
StringBuilder builder = new StringBuilder();
String url = builder.append("http://")
.append(getHostName())
.append(":")
.append(getPort())
.toString();
return url;
}
public void start() throws Exception {
server.start();
}
public void stop() throws Exception {
server.stop();
server.destroy();
}
}
package org.mikeneck.jfx.handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @author: mike
* @since: 12/02/22
*/
public class RequestHandler extends AbstractHandler {
private Server server;
public RequestHandler(Server server) {
this.server = server;
}
@Override
public void handle(String target,
Request request,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)
throws IOException, ServletException {
System.out.println("request : " + target);
if ("/".equals(target)) {
httpServletResponse.setStatus(200);
PrintWriter writer = httpServletResponse.getWriter();
File file = new File("src/test/resources/index.html");
FileReader reader = null;
try {
reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
while (bufferedReader.ready()) {
String line = bufferedReader.readLine();
writer.write(line);
writer.write('\n');
}
} finally {
reader.close();
writer.flush();
}
} else if ("/js/test.js".equals(target)) {
httpServletResponse.setStatus(200);
PrintWriter writer = httpServletResponse.getWriter();
File file = new File("src/test/resources/js/test.js");
FileReader reader = null;
try {
reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
while (bufferedReader.ready()) {
String line = bufferedReader.readLine();
writer.write(line);
writer.write('\n');
}
} finally {
reader.close();
writer.flush();
}
} else if ("/end".equals(target)) {
httpServletResponse.setStatus(200);
httpServletResponse.getWriter().flush();
this.server.destroy();
}
}
}
function numberTest(arg) {
return 1 + arg;
}
function stringTest(arg) {
return arg + "_" + "test";
}
function objectTest(arg) {
arg.test = 'value';
return arg;
}
(function() {
var element = document.getElementById('loaded');
element.innerText = 'loaded';
})();
package org.mikeneck.jfx;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author: mike
* @since: 12/03/04
*/
public class TestBrowser extends Application {
private static TestBrowser instance;
private static boolean ready = false;
private WebEngine webEngine;
private BlockingQueue<String> script;
@Override
public void start(Stage stage) throws Exception {
instance = this;
String url = getUrl();
webEngine = new WebEngine();
webEngine.load(url);
ready = true;
}
private String getUrl() throws IllegalStateException {
Parameters parameters = getParameters();
List<String> params = parameters.getRaw();
if (params == null || params.size() == 0) {
throw new IllegalStateException("Url is not defined.");
}
return params.get(0);
}
public static TestBrowser getInstance() throws IllegalStateException {
if (instance == null) {
throw new IllegalStateException("Java FX Application is not launched.");
}
return instance;
}
public static boolean isReady() {
if (instance == null) {
return false;
}
return ready;
}
public void shutdown() {
Platform.runLater(
new Runnable() {
@Override
public void run() {
Platform.exit();
ready = false;
instance = null;
}
}
);
}
public <T> T runScript(String source, final Class<T> expectedClass) throws InterruptedException, ClassCastException {
script = new LinkedBlockingQueue<>();
script.put(source);
final BlockingQueue<T> results = new LinkedBlockingQueue<>();
Platform.runLater(
new Runnable() {
@Override
public void run() {
try {
/** for synchronization of loading contents **/
Document document = webEngine.getDocument();
Element element = document.getElementById("loaded");
String content = element.getTextContent();
while ("".equals(content)) {
Thread.sleep(100);
element = document.getElementById("loaded");
content = element.getTextContent();
}
String command = script.take();
Object result = webEngine.executeScript(command);
T castedResult = expectedClass.cast(result);
results.put(castedResult);
} catch (InterruptedException e) {
e.printStackTrace();
try {
results.put(null);
} catch (InterruptedException e1) {
}
}
}
}
);
return results.take();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment