Sunday 24 October 2010

GWT 2.0 - JRE Presenter Test: ERROR: GWT.create() is only usable in client code!

I was writing JRE Test for one of my presenter classes. My presenter has display interface, which is implemented by view. As usual, I mocked out display interface in my presenter class.
mockDisplay = createStrictMock(EditInterviewPresenter.Display.class);
Hovewer, when I tried to run the test I received an exception:
java.lang.UnsupportedOperationException: ERROR: GWT.create() is only usable in client code! It cannot be called, for example, from server code. If you are running a unit test, check that your test case extends GWTTestCase and that GWT.create() is not called from within an initializer or constructor.
The source of a problem was method deleteQuestionAnswerPanel from display interface. One of the parameters is PushButton object, which is of type UIObject:
void deleteQuestionAnswerPanel(Long id, PushButton deleteButton);
EasyMock uses reflection mechanism of java, and in the process...
public static Class<?> forName(String name, boolean initialize, ClassLoader loader)
... method is called for display interface method parameters. Furthermore, this method is called with initialize parameter set to true, which means that static fields will be initialized. And UIObject class contains one very specific static field that causes an exception:
private static DebugIdImpl debugIdImpl = GWT.create(DebugIdImpl.class);
Solution:

1) Use types like HasText, HasClickHandlers insteed of UIObject types.
2) Before creating mock object, call: GWTMockUtilities.disarm()
Replace the normal GWT.create() behavior with a method that returns null instead of throwing a runtime exception. This is to allow JUnit tests to mock classes that make GWT.create() calls in their static initializers. This is not for use with GWTTestCase, and is not for use testing widgets themselves. Rather, it is to allow pure java unit tests of classes that need to manipulate widgets.

1 comment:

  1. Missing GWTMockUtilities.disarm() was my problem. Thanks!

    ReplyDelete