[Unit Test] Is there a way to mock JSONObject?

2,710 views
Skip to first unread message

Kevin Q

unread,
Feb 2, 2010, 4:19:47 PM2/2/10
to Google Web Toolkit
Our application consumes JSON web services. We're using JSONParser,
returning a JSONObject, and construct domain models from the result
JSONObject. I'd like to test that piece of code, but it seems I cannot
use JSONObject in JVM unit tests, as it depends on native code.

java.lang.UnsatisfiedLinkError:
com.google.gwt.core.client.JavaScriptObject.createObject()Lcom/google/
gwt/core/client/JavaScriptObject;
at com.google.gwt.core.client.JavaScriptObject.createObject(Native
Method)
at com.google.gwt.json.client.JSONObject.<init>(JSONObject.java:46)
[output cut...]

I'm wondering is there a way to mock JSONObject, use a hash map to
hold the key/value pairs, which enables me to run these tests in JVM?
JSONObject is an interface, so EasyMock can't help here. (correct me
if I'm wrong)

Also, I tried creating a class MockJSONObject extending JSONObject,
and replace the put/get logic with HashMap based implementation but
still no avail, because the JSONObject constructor calls native JS
code as well...

Any input is appreciated.

Carlos Aguayo

unread,
Feb 2, 2010, 6:38:59 PM2/2/10
to Google Web Toolkit
Not as good or ideal as a mockobject but you could use the
GWTTestCase.

Thomas Broyer

unread,
Feb 3, 2010, 11:25:56 AM2/3/10
to Google Web Toolkit

I'd suggest giving up on using JSONObject altogether. I'm modeling my
objects as interfaces and have them implemented by a JavaScriptObject,
I parse a JSON string using JsonUtils.unsafeParse(). That way I can
easily mock the interface in unit tests.
I don't serialize objects to JSON, but if I were to do it, I'd
probably use "new JSONObject(jso).toString()", which can easily be
"hidden" (as well as the JsonUtils.unsafeParse) in a JSON class with
parse/stringify methods. You could easily switch between using a pure-
Java library or JsonUtils/JSONObject using <super-source/> (two
versions of the JSON class, one in pure-Java that is used in DevMode
and pure-Java tests, and one to be compiled to JS)

Reply all
Reply to author
Forward
0 new messages