Posts Tagged ‘code’

Java-based JavaScript unit testing with Rhino


At SwissProt, we test the UniProt website in several ways (though we still lack coverage, which is another topic). One area where testing was lacking for some time was JavaScript, which had accumulated over time to a somewhat substantial amount, about 3200 lines of code. We have Selenium tests for the site as a whole, but having unit tests for individual bits of JavaScript would have been great to make development of new code easier, and increase confidence in the code.

Many available frameworks such as JsUnit do in-browser testing. If you want to test actual UI code, that’s obviously what you need. But we have that at least partly covered with Selenium, and a problem with these tests is that they are difficult to run in an automated way, like from our ant test task. So I wanted something to easily and quickly test the UI-independent code, along with the Java code, from the command line, ant, or scripts. I also think that a standard JUnit-style test is way easier to write, but I guess that depends on what you’re used to.

Having read about Mozilla Rhino several times, a JavaScript interpreter written in Java with good integration between the two languages, I set out to see how much work it could be to write a simple test framework. As it turned out, it wasn’t much work at all, and there’s so little code that I can show all of it in this post.



Examining invalid UTF


Recently we had this problem at work: Invalid UTF-8 start byte 0xb4 (at char #664428955, byte #664427999)
No one was exactly sure about the best way to debug this, so I set out to hack something together.

Here’s a Java program that reads bytes from a UTF-8 file and tries to interpret them as a UTF-8 string. If it succeeds, the string is printed, else if there’s an exception, the stack trace is printed. Usage:

$ java -cp "." ByteToUtfReader file.rdf 679609087 1000

reads byte 679609087 and the 1000 bytes preceding it from file.rdf.

Here’s the code in case it helps someone. Warning: quick and dirty!