Can Your Java Code Run in a Browser? Yes, it can!

JUnit Browser Runner is a small and very handy extension of JUnit. It is a small step for the DukeScript project, but a giant leap forward for the Java community: The JUnit Browser Runner gives you very easy way to verify whether your Java code runs in browser or not.

Start from command line

Of course, if you are an IDE junkie, you may prefer a visual way of getting started, but to prove that it is really just a matter of a few commands, let’s set everything up from a command line. Install Java, install Maven and invoke:

$ mvn archetype:generate \
  -DarchetypeGroupId=com.dukescript.archetype \
  -DarchetypeArtifactId=knockout4j-archetype \
  -Dwebpath=client-web \
  -DgroupId=org.your.test \
  -DartifactId=yesican \
  -Dversion=1.0-SNAPSHOT \
  -DarchetypeVersion=0.13 # or newer version
$ cd yesican
$ mvn install

and that is it! Please note that a browser has been opened and it executed Java JUnit. Just three shell commands and you have all the environment you need!

Test You Code!

The previous test run succeeded, but not everything works the same in the browser as in a classical desktop Java application. Let’s write a test that shows some difference. Open the existing DataModelTest.java file in your favorite text editor:

$ vi client/src/test/java/org/your/test/DataModelTest.java

and insert a new testing method into it:

@Test
public void temporaryFile() throws Exception {
    java.io.File.createTempFile("prefix", ".suffix");
}

This is a classical JUnit code - e.g. nothing special - a single test method annotated by JUnit’s @Test annotation that tries to create a temporary file. That succeeds on desktop, but fails in the current browser environment. Let’s try it:

$ mvn -f client/pom.xml test

Again a browser page is opened, it runs your your Java code, and shows a failure. The Maven test execution ends with an error. Please note the Details link that you gives you a chance to re-Run Again your code and more easily find out what is wrong.

Run Your own Code!

Now you are just a step towards running your own code. Modify the client Maven project to reference your libraries and code. Write a simple @Test method. Then the system handles the rest. It smoothly runs your Java code for you on desktop as well as in a browser!

You can control in which browser your Java code runs. Just specify junit.browser property when setting the the command line up:

$ mvn -f client/pom.xml test -Djunit.browser=chromium-browser
$ mvn -f client/pom.xml test -Djunit.browser=firefox

Enjoy JUnit Browser Runner!