Git Product home page Git Product logo

gwtmockito's Introduction

What is GwtMockito?

Testing GWT applications using GWTTestCase can be a pain - it's slower than using pure Java tests, and you can't use reflection-based tools like mocking frameworks. But if you've tried to test widgets using normal test cases, you've probably run into this error:

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.

GwtMockito solves this and other GWT-related testing problems by allowing you to call GWT.create from JUnit tests, returning Mockito mocks.

How do I use it?

Getting started with GwtMockito using Junit 4.5+ is easy. Just annotate your test with @RunWith(GwtMockitoTestRunner.class), then any calls to GWT.create encountered will return Mockito mocks instead of throwing exceptions:

@RunWith(GwtMockitoTestRunner.class)
public class MyTest {
  @Test
  public void shouldReturnMocksFromGwtCreate() {
    Label myLabel = GWT.create(Label.class);
    when(myLabel.getText()).thenReturn("some text");
    assertEquals("some text", myLabel.getText());
  }
}

GwtMockito also creates fake implementations of all UiBinders that automatically populate @UiFields with Mockito mocks. Suppose you have a widget that looks like this:

public class MyWidget extends Composite {
  interface MyUiBinder extends UiBinder<Widget, MyWidget> {}
  private final MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

  @UiField Label numberLabel;
  private final NumberFormatter formatter;

  public MyWidget(NumberFormatter formatter) {
    this.formatter = formatter;
    initWidget(uiBinder.createAndBindUi(this);
  }

  void setNumber(int number) {
    numberLabel.setText(formatter.format(number));
  }
}

When createAndBindUi is called, GwtMockito will automatically populate numberLabel with a mock object. Since @UiFields are package-visible, they can be read from your unit tests, which lets you test this widget as follows:

@RunWith(GwtMockitoTestRunner.class)
public class MyWidgetTest {

  @Mock NumberFormatter formatter;
  private MyWidget widget;

  @Before
  public void setUp() {
    widget = new MyWidget(formatter);
  }

  @Test
  public void shouldFormatNumber() {
    when(formatter.format(5)).thenReturn("5.00");
    widget.setNumber(5);
    verify(widget.numberLabel).setText("5.00");
  }
}

Note that GwtMockito supports the @Mock annotation from Mockito, allowing standard Mockito mocks to be mixed with mocks created by GwtMockito.

That's all you need to know to get started - read on if you're interested in hearing about some advanced features.

Accessing the mock returned from GWT.create

Returning mocks from GWT.create isn't very useful if you don't have any way to verify or set behaviors on them. You can do this by annotating a field in your test with @GwtMock - this will cause all calls to GWT.create for that type to return a mock stored in that field, allowing you to reference it in your test. So if you have a class that looks like

public class MyClass {
  public MyClass() {
    SomeInterface myInterface = GWT.create(SomeInterface.class);
    myInterface.setSomething(true);
  }
}

then you can verify that it works correctly by writing a test that looks like this:

@RunWith(GwtMockitoTestRunner.class)
public class MyClassTest {
  @GwtMock SomeInterface mockInterface;

  @Test
  public void constructorShouldSetSomething() {
    new MyClass();
    verify(mockInterface).setSomething(true);
  }
}

Returning fake objects

By default, GwtMockito will return fake implementations (which don't require you to specify mock behavior) for any classes extending the following types:

  • UiBinder
  • ClientBundle
  • Messages
  • CssResource
  • SafeHtmlTemplates

You can add fakes for additional types by invoking GwtMockito.useProviderForType(Class, FakeProvider) in your setUp method. This will cause all calls to GWT.create for the given class or its subclasses to invoke the given FakeProvider to determine what to return. See the javadoc reference for more details.

Mocking final classes and methods

Mockito does not normally allow final classes and methods to be mocked. This poses problems in GWT since JavaScript overlay types (which include Element and its subclasses) require all methods to be final. Fortunately, GwtMockito does some classloader black magic to remove all final modifiers from classes and interfaces, so the following test will pass:

@RunWith(GwtMockitoTestRunner.class)
public class MyTest {
  @Mock Element element;

  @Test
  public void shouldReturnMocksFromGwtCreate() {
    when(element.getClassName()).thenReturn("mockClass");
    assertEquals("mockClass", myLabel.getClassName());
  }
}

As long as your test uses GwtMockitoTestRunner, it is possible to mock any final methods.

Dealing with native methods

Under normal circumstances, JUnit tests will fail with an UnsatisfiedLinkError when encountering a native JSNI method. GwtMockito works around this problem using more classloader black magic to provide no-op implementations for all native methods using the following rules:

  • void methods do nothing.
  • Methods returning primitive types return the default value for that type (0, false, etc.)
  • Methods returning Strings return the empty string.
  • Methods returning other objects return a mock of that object configured with RETURNS_MOCKS.

These rules allow many tests to continue to work even when calling incindental native methods. Note that this can be dangerous - a JSNI method that normally always returns true would always return false when stubbed by GwtMockito. As much as possible, you should isolate code that depends on JSNI into its own class, inject that class into yours, and test the factored-out class using GWTTestCase.

Support for JUnit 3 and other tests that can't use custom runners

Though GwtMockitoTestRunner is the easiest way to use GwtMockito, it won't work if you're using JUnit 3 or rely on another custom test runner. In these situations, you can still get most of the benefit of GwtMockito by calling GwtMockito.initMocks directly. A test written in this style looks like this:

public class MyWidgetTest extends TestCase {

  private MyWidget widget;

  @Override
  public void setUp() {
    super.setUp();
    GwtMockito.initMocks(this);
    widget = new MyWidget() {
      protected void initWidget(Widget w) {
        // Disarm for testing
      }
    };
  }

  @Override
  public void tearDown() {
    super.tearDown();
    GwtMockito.tearDown();
  }

  public void testSomething() {
    // Test code goes here
  }
}

The test must explicitly call initMocks during its setup and tearDown when it is being teared down, or else state can leak between tests. When instantiating a widget, the test must also subclass it and override initWidget with a no-op implementation, or else it will fail when this method attempts to call Javascript. Note that when testing in this way the features described in "Mocking final classes and methods" and "Dealing with native methods" won't work - there is no way to mock final methods or automatically replace native methods without using GwtMockitoTestRunner.

How do I install it?

If you're using Maven, you can add the following to your <dependencies> section:

<dependency>
  <groupId>com.google.gwt.gwtmockito</groupId>
  <artifactId>gwtmockito</artifactId>
  <version>1.1.9</version>
  <scope>test</scope>
</dependency>

You can also download the jar directly or check out the source using git from https://github.com/google/gwtmockito.git. In these cases you will have to manually install the jars for Mockito and Javassist.

Where can I learn more?

  • For more details on the GwtMockito API, consult the Javadoc
  • For an example of using GwtMockito to test some example classes, see the sample app.

Version history

1.1.9

  • Support ResourcePrototype methods in fake CLientBundles. (Thanks to zbynek)
  • Add a @WithExperimentalGarbageCollection annotation. (Thanks to LudoP)
  • Updated javassist dependency. (Thanks to TimvdLippe)

1.1.8

  • Preliminary Java 9 support. (Thanks to benoitf)

1.1.7

  • Update GWT to version 2.8.0.
  • Update Javassist to version 3.22.
  • Stubbing for ValueListBox. (Thanks to jschmied)
  • Stubbing for URL encoding. (Thanks to jschmeid)
  • Generate hashCode and equals for Messages. (Thanks to zolv)

1.1.6

  • Improved support for running tests in IntelliJ.
  • Fix for stubbing DatePicker.
  • Better support for non-default classloaders. (Thanks to leanseefeld)
  • Depend on mockito-core instead of mockito-all. (Thanks to psiroky)

1.1.5

  • Support for JUnit 4.12. (Thanks to selesse)
  • Provide a better error message for ClassCastExceptions that we can't work around.
  • Support for JaCoCo. (Thanks to rsauciuc)
  • Include a fake implementation of NumberConstants.
  • Fixed support for History methods.
  • Fix for some TextBox methods.
  • Fix instantiation of checkboxes and radio buttons.

1.1.4

  • Many fixes for ClassCastExceptions when mocking various classes.
  • Support for Cobertura coverage tools. (Thanks to mvmn)
  • Try to intelligently return the right value for getTagName when possible.
  • Fixed a classloader delegation issue. (Thanks to paulduffin)
  • Add an annotation allowing the excludelist of classes that are always loaded via the standard classloader to be specified on a per-test bases.

1.1.3

  • Support for Hamcrest matchers.
  • Added a method to specify packages that should never be reloaded.
  • Added a getFake method to provide direct access to registered fakes.
  • Fixed assertion errors in classes extending LabelBase.
  • Added an annotation allowing stubbed classes to be specified on a per-test basis (suggested by danielkaneider)
  • Support for GWT 2.6.
  • Fix to allow FakeProviders to be specified for RPC interfaces.

1.1.2

  • Fix for UiBinders that generate parameterized widgets.
  • Fix to always use the most specific provider available when multiple providers could provide a type. (Thanks to reimai)
  • Compatability with EMMA code coverage tools.

1.1.1

  • Fix for a bug in AsyncAnswers. (Thanks to tinamou)
  • Mock @GwtMock fields in superclasses the same way that Mockito does. (Thanks to justinmk)
  • Fix for a conflict with PowerMock.

1.1.0

  • Support for GWT-RPC by returning mock async interfaces when GWT.creating the synchronous interface
  • Support for testing widgets that expand Panel classes by automatically stubbing Panel methods.
  • Ability to customize classes that are automatically stubbed in order to support widgets extending third-party base classes.
  • Ability to customize the classloader and classpath used by GwtMockito for better tool integration.
  • More flexible FakeProviders that allow the returned type to be unrelated to the input type. Note that this can be a breaking change in some cases: getFake should now just take a Class<?> instsead of a Class<? extends T>. See here for an example.

1.0.0

  • Initial release

gwtmockito's People

Contributors

benoitf avatar csobrinho avatar cushon avatar dependabot[bot] avatar ekuefler avatar gkdn avatar jbarop avatar justinmk avatar leanseefeld avatar mkasztelnik avatar paulduffin avatar reimai avatar rsauciuc avatar selesse avatar tbroyer avatar timvdlippe avatar zbynek avatar zolv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gwtmockito's Issues

Mocked @UiField types are erased, causing ClassCastExceptions

The implementation of FakeUiBinderProvider erases the type of all of the fields it injects (e.g. Box<String> gets mocked as Box<Object>). It isn't possible to pass the necessary type information through GWT.create() (since it only takes a class literal), but there may be alternatives I'm missing.

Here's an example:

@RunWith(GwtMockitoTestRunner.class)
public class MyWidgetTest {

  interface Box<T> {
    T get();
  }

  static class MyWidget extends Composite {
    interface MyUiBinder extends UiBinder<Widget, MyWidget> {}
    private final MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

    @UiField
    Box<String> message;

    public MyWidget() {
      initWidget(uiBinder.createAndBindUi(this));
    }
  }

  MyWidget myWidget;

  @Before
  public void setUp() {
    myWidget = new MyWidget();
  }

  @Test
  public void simpleTest() {
    String message = myWidget.message.get();
  }
}

The mock for myWidget.message will be a raw Box, so get() returns a String, causing a ClassCastException:

java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$ef767c84 cannot be cast to java.lang.String
    at mockitobug.MyWidgetTest.simpleTest(MyWidgetTest.java:44)
        ...

I encountered this because if you write:

when(myWidget.message.get()).thenReturn("Hello");

Then the eclipse compiler will generate a string cast on the result of myWidget.message.get(), which causes the test to crash. (javac is unaffected, except for specific versions of javac9.)

Here's the complete repro:

mkdir -p src/test/java/mockitobug
curl https://gist.githubusercontent.com/cushon/50a9cbe451e7d6607a65/raw/8ccb8750c462b06d55109cfa2a6fcf7ff54f310c/MyWidgetTest.java > src/test/java/mockitobug/MyWidgetTest.java
curl https://gist.githubusercontent.com/cushon/50a9cbe451e7d6607a65/raw/94d77af02627d2b7b1756ff14e7a396514d7aeaa/pom.xml > pom.xml
mvn test
Running mockitobug.MyWidgetTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.565 sec <<< FAILURE!
simpleTest(mockitobug.MyWidgetTest)  Time elapsed: 0.237 sec  <<< ERROR!
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$ef7df407 cannot be cast to java.lang.String
    at mockitobug.MyWidgetTest.simpleTest(MyWidgetTest.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
...

java.lang.ClassCastException: com.google.gwt.user.client.Element$$EnhancerByMockitoWithCGLIB$$4fca3809 cannot be cast to com.google.gwt.dom.client.TableElement

I found #4 when Googling for help. I suspect this could be related.

I am trying to run a test that includes a CellTable and hit the following error.

java.lang.ClassCastException: com.google.gwt.user.client.Element$$EnhancerByMockitoWithCGLIB$$4fca3809 cannot be cast to com.google.gwt.dom.client.TableElement
    at com.google.gwt.user.cellview.client.CellTable.<init>(CellTable.java:613)
    at com.google.gwt.user.cellview.client.CellTable.<init>(CellTable.java:581)
    at com.github.gwtbootstrap.client.ui.CellTable.<init>(CellTable.java:110)
    at com.github.gwtbootstrap.client.ui.CellTable.<init>(CellTable.java:117)
    at com.github.gwtbootstrap.client.ui.CellTable.<init>(CellTable.java:121)
    at com.github.gwtbootstrap.client.ui.CellTable.<init>(CellTable.java:133)
    at com.github.gwtbootstrap.client.ui.CellTable.<init>(CellTable.java:105)

The Widget I'm attempt to test looks like this.

public class MyScreen extends Composite  {

    @UiField(provided = true)
    CellTable<String> table = new CellTable<String>();

The test code looks like this.

@RunWith(GwtMockitoTestRunner.class)
public class MyScreenTest {

    @GwtMock
    private CellTable<String> table;

I've tried with 1.1.3 but to no avail.

I could be doing something wrong; to be honest I'm new to GwtMockito, so wouldn't put user error out of the question.

gwtmockito&maven

Hi. I'm trying to write unit tests for our project using gwtmockito, but I have a problem: gwtmockito cannot find my test classes. I wrote simple test application with one test only.
My POM file:

<groupId>simple_test</groupId>
<artifactId>simple_test</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.9</version>
    </dependency>
    <dependency>
        <groupId>com.google.gwt.gwtmockito</groupId>
        <artifactId>gwtmockito</artifactId>
        <version>1.1.1</version>
    </dependency>
</dependencies>

My test:

package com.test;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(GwtMockitoTestRunner.class)
public class SimpleTest {

@Test
public void test() {

}

}

When I run it using maven I have an exception java.lang.ClassNotFoundException: caught an exception while obtaining a class file for com.test.SimpleTest. But it works ok when I run it in IntelliJ IDEA "Run 'SimpleTest'".

What am I doing wrong?

Thank you.

ClassCastException when trying to use AutoBeanCodex

I've posted a SO post describing my problem, here.
But to restate, I'm getting the following exception when trying to decode some autobeans.
java.lang.ClassCastException: com.google.web.bindery.autobean.shared.AutoBean$$EnhancerByMockitoWithCGLIB$$78caf05b cannot be cast to com.google.web.bindery.autobean.shared.impl.AbstractAutoBean
at com.google.web.bindery.autobean.shared.impl.AutoBeanCodexImpl.doDecode(AutoBeanCodexImpl.java:549)
at com.google.web.bindery.autobean.shared.AutoBeanCodex.decode(AutoBeanCodex.java:39)
at ...

I'd like to have actual autobean instances that can be encoded/decoded by the autobean codex. This would allow my to test that my methods which are translating JSON into autobeans are working appropriately.

So, how should I approach this?

How to mock static methods?

I have a class like this:

public class Utilities{
public static int getValue(){
return 10;
}
}

I want to write test for this class:

public class ServiceClass{
public void populate(){
if(Utilities.getValue() < 15){

}
}
}

Is it possible to mock what Utilities.getValue() return?

java.lang.ClassCastException: com.google.gwt.user.client.Element$$EnhancerByMockitoWithCGLIB$$492e40ea cannot be cast to com.google.gwt.dom.client.InputElement

When i test a wiget which include some textbox got the error.

Java.lang.ClassCastException: com.google.gwt.user.client.Element$$EnhancerByMockitoWithCGLIB$$492e40ea cannot be cast to com.google.gwt.dom.client.InputElement
    at com.google.gwt.user.client.ui.TextBox.getInputElement(TextBox.java:137)
    at com.google.gwt.user.client.ui.TextBox.setMaxLength(TextBox.java:124)
    at xxxx.EndPointWidget.initForm(EndPointWidget.java:62)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:301)

Target class is here:

 private final TextBox serveripValueWidget = new TextBox();
 public EndPointWidget() {
        initForm();
  }

 private void initForm() {
        serveripValueWidget.setMaxLength(50);
}

Test case is here:

    @Test
    public void setData() {
        EndPointWidget epw = new EndPointWidget(); //error happen.
    }

Snapshots repository of the GwtMockito

Hello!
Are planing to create the snapshots repository of the library? Otherwise we need to install it in the local environment.
Also I'm wondering ,what is a plan for releasing the version 1.0.1?

Used with History, doesn't works

I use @RunWith(GwtMockitoTestRunner.class) on my test class, all is fine, I don't got the message about the client problem. My test scenario is that I call History.newItem(token) and after this I use History.getToken(). getToken will always return "", but it should have the token which I gave into newItem. impl = GWT.create(HistoryImpl.class), HistoryImpl is mocked by GwtMockio automatically(?) but impl is null and thats the problem. At the moment I don't know how to fix it, is there any solution, smth what I have forgotten?

Regards

Chris

ClassCastException when a GwtBootstrap Button is instanced

I'm using GwtMockito v1.1.4 for tests and I use GwtBootstrap in my project.
I'm getting this exception when I instantiate my widget :

java.lang.ClassCastException: com.google.gwt.dom.client.Text$$EnhancerByMockitoWithCGLIB$$bfd15ee6 cannot be cast to com.google.gwt.dom.client.Element
    at com.github.gwtbootstrap.client.ui.base.TextNode.setText(TextNode.java:34)
    at com.github.gwtbootstrap.client.ui.base.TextNode.<init>(TextNode.java:19)
    at com.github.gwtbootstrap.client.ui.base.IconAnchor.<init>(IconAnchor.java:75)
    at com.github.gwtbootstrap.client.ui.Button.<init>(Button.java:74)
    at com.github.gwtbootstrap.client.ui.Button.<init>(Button.java:95)
    at fr.mycompany.ga.client.ui.mainWidgets.userContent.UserContentImpl.<init>(UserContentImpl.java:52)
    at fr.mycompany.ga.client.ui.mainWidgets.userContent.UserContentTest.setUp(GreenUserContentTest.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:301)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

I tried using GwtMockito V 1.1.5-SNAPSHOT, but I'm getting an error related to "com.google.gwt.user.client.impl.HistoryImpl".

I'm just crating a new Button in my constructor, I'm trying to find a workaround.

AssertionError in LabelBase

Hi guys,
I am using gwtmockit 1.1.2 with gwt 2.5.0 to write tests for a MVP Application.
One of my Tests creates an AssertionError, a simple Testcase that reproduces the Problem looks like this:

@Test
public void featureTest() {
    InlineHTML inline = new InlineHTML("hello world");
    assertNotNull(inline);
}

this creates the following stacktrace:

java.lang.AssertionError
at com.google.gwt.user.client.ui.LabelBase.(LabelBase.java:61)
at com.google.gwt.user.client.ui.LabelBase.(LabelBase.java:57)
at com.google.gwt.user.client.ui.Label.(Label.java:199)
at com.google.gwt.user.client.ui.HTML.(HTML.java:168)
at com.google.gwt.user.client.ui.InlineHTML.(InlineHTML.java:79)
at com.google.gwt.user.client.ui.InlineHTML.(InlineHTML.java:125)

I am using
@RunWith(GwtMockitoTestRunner.class)
am i doing something wrong or is this a know limitation?
thanks for your help!

Events subsystem is not testable

Hello! I've tried to test some widget behavior , but failed since my code operating on GWT event and handler manager. Will you support testing of GWTEvents? As i see you are mocking the EventBus object, that's why the event doesn't intercepted by registered Handlers.

I've tried to perform events testing in the composite with EventBus created by hand and everything worked perfectly.
So far ensureHandlerMehtod should return the real bus and not the mock.
Thanks!

Problem mocking RPC interface creation

A common pattern when using GWT-RPC is the following:

SomeRemoteServiceAsync asyncService = GWT.create(SomeRemoteService.class);

You use a reference to the asynchronous version, but to create the async implementation you specify the synchronous version of the RPC interface in the GWT.create() factory. The GWT.create() factory know that it needs to return an implementation of the async version in this case.

This pattern is currently not possible to mock with GwtMockito. The mocking facility of GWT.create() returns a mock for the SomeRemoteService class, instead of the required async interface, and a class cast exception is the result.

GwtMockito offers the GwtMockito.useProviderForType(Class, FakeProvider) facility, but this doesn't help us in this case since the method is typed and you can't let the FakeProvider return a different interface than expected by the provided Class.

I think we could make use of the fact that the synchronous versions of the RPC interfaces always extend the RemoteService interface. The mock GWT.create() factory could check for this interface and try to load and mock the asynchronous version. Another possibility would be to extend/refactor the GwtMockito.useProviderForType() method to allow to return a different class then the class that is specified as a parameter.

If GwtMockito could also seamlessly mock RPC interfaces than it would be an almost perfect solution! :)

Cheers,
Ben

Problem running tests with GwtMockitoTestRunner when classpath is assembled at runtime

Hi,

first I want to say that the GwtMockito lib is really a very nice and promising approach that would benefit us much in testing our GWT client code!

Currently, I'm blocked by a problem to programmatically run the tests with the GwtMockitoTestRunner. When I create a test and use the @RunWith annotation and then use the IntelliJ IDE JUnit test runner to run the class (right-click on the test class) it works. The JUnit runner runs the "java" commands and passes all libs and folders via the -classpath parameter (which is a lot! ;)).

Now I want to run the test from within the Grails framework. The problem is (I believe) that the test classpath is assembled at runtime and before running the tests the current thread's contextClassLoader is modified with all the required libs and folders etc. When I now want to programmatically invoke the GwtMockitoTestRunner the problem is that the custom GwtMockitoClassLoader can't find my test class. The test class is found by the Thread classLoader though.

I'm not really familiar with the JUnit test runner internals, but the only thing I can imagine is that the GwtMockitoClassLoader respects classloader resources passed when the application is started, but not the current context classLoader of the thread?

I checked the sources for the GwtMockitoTestRunner.java and the GwtMockitoClassLoader and it seems that the initialization is done in the constructor and the classloader class is private, so there is no hook to interfere with the classloader resource locations...

I know this description is rather vague, but maybe you already have an idea what the problem may be? If you require additional information I would be happy to provide them.

Maybe we could also produce a small code snippet that show how the GwtTestRunner can be invoked on a test class / test classes in a programmatic way?

Thank you!

Cheers,
Ben

Unable to test method that new's a CellList

Hi there,

I'm trying to test a class which has a @UiFactory method in it that creates a CellList; however, I have been unable to get this working so far... I've tried the following approaches and had the following results:

Approach Result
Just using the standard GwtMockitoTestRunner java.lang.ClassCastException: com.google.gwt.user.client.Element$$EnhancerByMockitoWithCGLIB$$19f20bd7 cannot be cast to com.google.gwt.dom.client.DivElement
Using a custom runner that adds CellList to the list of classes to be stubbed java.lang.NoClassDefFoundError: com/google/gwt/user/cellview/client/CellList
Using the @WithClassesToStub annotation to provide the CellList as a class to be stubbed out java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy

I have a checked in a sample project that shows the problems I'm having to the following location: https://github.com/jamiecramb/gwtmockito-celllist-problem.

Thanks in advance.

Cheers,
Jamie

Unable to run tests with GwtMockitoTestRunner in IDEA

See latest comments on #5 for one possible resolution.

It would be nice to get a release of either the current master or something that directly incorporates context classloader instead of system classloader into the class lookup mechanism.

Cannot mock 'LocaleInfo.getAvailableLocaleNames' (1.1.3->1.1.4 Regression)

In 1.1.3 it was possible to mock LocaleInfo#getAvailableLocaleNames() easily:

@GwtMock LocaleInfo localeInfo;

@Test
public void myTest() {
  when(LocaleInfo.getAvailableLocaleNames()).thenReturn(new String[] { "foo" });
  ... test stuff.
}

In 1.1.4, due to c5465ca making the LocaleInfo(Impl) a fake, this doesn't work. And, because one cannot replace the default fakes either, this essentially means my tests for locale/i18n can no longer run :/

With that said, I worked around the issue like this:

@RunWith(GwtMockitoTestRunner.class)
public class AppControllerTest {
    private static class MyFakeLocaleInfoImplProvider implements FakeProvider<LocaleInfoImpl> {
        /** If non-{@code null}: locale names to return from {@link LocaleInfo#getAvailableLocaleNames()} */
        private static String[] availableLocaleNames = null;

        public static void setAvailableLocaleNames(String... availableLocaleNames) {
            MyFakeLocaleInfoImplProvider.availableLocaleNames = availableLocaleNames;
        }

        @SuppressWarnings("unchecked")
        public static void enable() {
            try {
                Field field = GwtMockito.class.getDeclaredField("DEFAULT_FAKE_PROVIDERS");
                field.setAccessible(true);
                ((Map<Class<?>, FakeProvider<?>>) field.get(null)).put(LocaleInfoImpl.class, new MyFakeLocaleInfoImplProvider());
            } catch (NoSuchFieldException|SecurityException|IllegalArgumentException|IllegalAccessException e) {
                throw new RuntimeException("Cannot enable custom locales");
            }
        }

        @Override
        public LocaleInfoImpl getFake(Class<?> type) {
            return new LocaleInfoImpl() {
                @Override
                public DateTimeFormatInfo getDateTimeFormatInfo() {
                    return new DefaultDateTimeFormatInfo();
                }

                @Override
                public String[] getAvailableLocaleNames() {
                    return availableLocaleNames != null ? availableLocaleNames : super.getAvailableLocaleNames();
                }
            };
        }
    }

    @BeforeClass
    public static void setUpBeforeClass() {
        // Replace the fake LocaleInfoImpl with one that allows controlling the result of #getAvailableLocaleNames()
        // As this is a default provider we need to be quite aggressive in replacing it.
        MyFakeLocaleInfoImplProvider.enable();
    }

    @Test
    public void myTest() {
        final String localeName = "foo_BAR";
        MyFakeLocaleInfoImplProvider.setAvailableLocaleNames("foo");
        // do some testing!
    }

It would be nice if this was a tad easier to accomplish:

  • don't use anonymous classes in the default FakeProviders, so one can inherit and extend GwtMockito's fakes if needed
  • allow replacing the default fake providers (maybe using an annotation pointing to the fake provider class to use?)

Mocked UiBinder type is erased

I think is is distinct from #50.

In the following example the type of the UiBinder is erased when it is mocked, causing a ClassCastException.

I think there's type information available at runtime that could be used to fixed this. For example, see mockito's handling of RETURNS_DEEP_STUBS with generic types:

Here's the example:

@RunWith(GwtMockitoTestRunner.class)
public class MyWidgetTest {

  interface Appearance {
    // Mocked type will be erased to `UIBinder`
    UiBinder<? extends Widget, ?> uiBinder();
  }

  static class Widget {
    public Widget() {
      Appearance appearance = GWT.create(Appearance.class);
      // Assignment fails with CCE
      Widget widget = appearance.uiBinder().createAndBindUi(null);
    }
  }

  @Before
  public void setUp() {
    new Widget();
  }

  @Test
  public void simpleTest() {
    System.err.println("Hello world");
  }
}

Full repro:

mkdir -p src/test/java/mockitobug/
curl https://gist.githubusercontent.com/cushon/8c231f89708dadcf0075/raw/d9e50510499132037cac47dbd8ad67854fe8b429/MyWidgetTest.java > src/test/java/mockitobug/MyWidgetTest.java
curl https://gist.githubusercontent.com/cushon/50a9cbe451e7d6607a65/raw/94d77af02627d2b7b1756ff14e7a396514d7aeaa/pom.xml > pom.xml
mvn test
Running mockitobug.MyWidgetTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.514 sec <<< FAILURE!
simpleTest(mockitobug.MyWidgetTest)  Time elapsed: 0.216 sec  <<< ERROR!
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$99e9e895 cannot be cast to mockitobug.MyWidgetTest$Widget
    at mockitobug.MyWidgetTest$Widget.<init>(MyWidgetTest.java:22)
    at mockitobug.MyWidgetTest.setUp(MyWidgetTest.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        ...

gwtmockito + gwtquery

One hurdle that I can't seem to get over when trying to unit test views is I often use gwtquery. Unfortunately, using gwtquery makes for untestable views.

Do you think a collaboration between you and @jDramaix would be possible in order to make gwtquery play nice with gwtmockito? gwtquery seems like a very popular library in the GWT world, so it would make sense to allow it within a unit test context.

Thanks a lot for your great work :)

getting GwtMockitoTestRunner$FailedCastException in DateBox

To create a DateRange widget we are extending gwt DateBox but when I try to test the class that uses it I am getting this exception. I see that you fixed it for DatePicker but I wonder if it is also fixed for DateBox as I am still getting this error.

Caused by: java.lang.ClassCastException: com.google.gwt.dom.client.Element$$EnhancerByMockitoWithCGLIB$$57c66b4f cannot be cast to com.google.gwt.user.client.Element

Hi i am facing the below exception while using Mockito 1.1.4 for creating junit test case for my GWT class, can some help me fixing it

Exception :

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.google.gwtmockito.GwtMockitoTestRunner.withBefores(GwtMockitoTestRunner.java:326)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:261)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:307)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.google.gwtmockito.GwtMockitoTestRunner.withBefores(GwtMockitoTestRunner.java:324)
... 16 more
Caused by: java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor1.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
at org.mockito.Mockito.mock(Mockito.java:1243)
at org.mockito.Mockito.mock(Mockito.java:1120)
at com.google.gwtmockito.GwtMockito.registerGwtMocks(GwtMockito.java:203)
at com.google.gwtmockito.GwtMockito.initMocks(GwtMockito.java:133)
... 21 more
Caused by: java.lang.ClassCastException: com.google.gwt.dom.client.Element$$EnhancerByMockitoWithCGLIB$$57c66b4f cannot be cast to com.google.gwt.user.client.Element
at com.extjs.gxt.ui.client.core.El.isBorderBox(El.java:156)
at com.extjs.gxt.ui.client.GXT.init(GXT.java:317)
at com.extjs.gxt.ui.client.widget.Component.(Component.java:203)
... 35 more

GwtMockitoTestRunner does not work for JUnit <= 4.4

The README suggests that gwtmockito's GwtMockitoTestRunner is compatible with JUnit 4.x ("Getting started with GwtMockito using Junit 4 is easy."), when in fact it needs version >= 4.5.
With version 4.4 you get the following exception:

java.lang.NoSuchFieldError: NULL
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:57)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
    at com.google.gwtmockito.GwtMockitoTestRunner.<init>(GwtMockitoTestRunner.java:114)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.junit.internal.requests.ClassRequest.buildRunner(ClassRequest.java:33)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:28)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

According to a question on StackOverflow, this is because the required class was introduced in JUnit 4.5.
Unless I'm missing something, I think it should be stated explicitly which version of JUnit is actually supported.

PS: Great piece of black magic classloader sorcery :)

ClassCastException: cannot be cast to com.google.gwt.dom.client.AnchorElement

I am new to gwtmockito and I really like it. But here is an issue that caught me.

A simplified class is like this
// a class needs to be tested
public class MyClass {
Anchor obj;

public MyClass(String userName) {
        //this will fail with GwtMockito
        obj= new Anchor();
}

}

the class to test it is:
//a test class
@RunWith(GwtMockitoTestRunner.class)
public class MyClass_Test {
MyClass app;

@Before
public void setUp() {
    //this will fail with GwtMockito
    app = new MyClass("");
}

@Test
public void test1() {
    Assert.assertTrue(true);
}

}

however, when I run this test code, I get an error like this

java.lang.ClassCastException: com.google.gwt.user.client.Element$$EnhancerByMockitoWithCGLIB$$86942b16 cannot be cast to com.google.gwt.dom.client.AnchorElement
at com.google.gwt.dom.client.AnchorElement.as(AnchorElement.java:34)
at com.google.gwt.user.client.ui.Anchor.getAnchorElement(Anchor.java:564)
at com.google.gwt.user.client.ui.Anchor.(Anchor.java:119)
at com.google.gwt.user.client.ui.Anchor.(Anchor.java:104)
at com.sample.failed.MyClass.(MyClass.java:13)
at com.sample.failed.MyClass_Test.setUp(MyClass_Test.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:284)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

I am using gwtmockito 1.1.3 and gwt v2.5.1 with eclipse Kepler v4.3 (x64). GWT doesn't seem to like "new Anchor()" with gwtmockito. can you help me on this??

PS, it seems to make the code quoted automatically but improperly, not sure how to make it right, sorry about that.

thanks,

Edit:
This seems very common with GWT classes. Here is another example:
java.lang.ClassCastException: com.google.gwt.user.client.Element$$EnhancerByMockitoWithCGLIB$$44131348 cannot be cast to com.google.gwt.dom.client.SelectElement
at com.google.gwt.user.client.ui.ListBox.getSelectElement(ListBox.java:600)
at com.google.gwt.user.client.ui.ListBox.insertItem(ListBox.java:346)
at com.google.gwt.user.client.ui.ListBox.insertItem(ListBox.java:328)
at com.google.gwt.user.client.ui.ListBox.insertItem(ListBox.java:295)
at com.google.gwt.user.client.ui.ListBox.addItem(ListBox.java:173)

addItem is called by MyClass, but when testing MyClass, this error occurs. can't GwtMockito handle casting within GWT classes?

Please help.... this makes me desperate.

A widget that has an existing parent widget may not be added to the detach list

I try to test my view with GwtMockito and have this problem:

java.lang.AssertionError: A widget that has an existing parent widget may not be added to the detach list
    at com.google.gwt.user.client.ui.RootPanel.detachOnWindowClose(RootPanel.java:137)
    at com.google.gwt.user.client.ui.RootPanel.get(RootPanel.java:211)
    at com.google.gwt.user.client.ui.RootPanel.get(RootPanel.java:151)
    at com.ait.lienzo.client.core.shape.Node.<clinit>(Node.java:112)
    at sun.reflect.GeneratedSerializationConstructorAccessor17.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40)
    at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59)
    at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
    at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
    at org.mockito.Mockito.mock(Mockito.java:1243)
    at org.mockito.Mockito.mock(Mockito.java:1216)
    at com.google.gwtmockito.GwtMockito$Bridge.create(GwtMockito.java:317)
    at com.google.gwt.core.shared.GWT.createImpl(GWT.java:83)
    at com.google.gwt.core.client.GWT.create(GWT.java:86)
    at online.draughts.rus.client.application.home.PlayComponentView.initEmptyDeskPanel(PlayComponentView.java:195)

I try to create LienzoPanel in PlayComponentView like this:

Layer initDeskRect = GWT.create(Layer.class);
Rectangle contour = GWT.create(Rectangle.class);
...
lienzoPanel = GWT.create(LienzoPanel.class);
lienzoPanel.setBackgroundLayer(initDeskRect);
...

I investigated that there is problem in Node.java:

static
{
    RootPanel.get().getElement().getStyle().setProperty("webkitTapHighlightColor", "rgba(0,0,0,0)");
}

Is this problem on side of Lienzo?

Linkage Error on org.hamcrest.Matcher type

Error received when assertThat() method called with Hamcrest matcher

@Test
    public void validateSearchResultCellRendering() {
        SearchResultCell cell = new SearchResultCell();
        cell.render(context, result, builder);
        String actualCellHTML = builder.toSafeHtml().asString();
/* Trying to replace this: */       
        assertTrue(actualCellHTML + " does not contain \"" + TITLE +"\"", actualCellHTML.contains(TITLE));
/* with this: */
        assertThat(actualCellHTML, org.hamcrest.Matchers.containsString(TITLE));
    }

Stack Trace

java.lang.LinkageError: loader constraint violation: loader (instance of sun/misc/Launcher$AppClassLoader) previously initiated loading for a different type with name "org/hamcrest/Matcher"
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:792)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:12)
    at org.junit.Assert.assertThat(Assert.java:865)
    at org.junit.Assert.assertThat(Assert.java:832)
    at com.sevencity.webapp.client.view.cell.SearchResultCellTest.validateSearchResultCellRendering(SearchResultCellTest.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:243)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Release 1.1.5 version

I need access to the recently commited changes for mocking RadioButton's

I've tested locally against the snapshot and it works (great for validating my widget) but I need a real release made so that I can commit my code against my local project since we have a rule against using -SNAPSHOT's

Would it be possible to make a new release that contains the most recent fixes?

Thanks

LayoutComposite requires that its wrapped widget implement RequiresResize

I have a widget which extends ResizeComposite, and I'm using the GwtMockitoTestRunner

The call inside the constructor initWidget(uiBinder.createAndBindUi(this)); fails with this exception because initWidget inside ResizeComposite has the following assert:

    assert widget instanceof RequiresResize :
      "LayoutComposite requires that its wrapped widget implement RequiresResize";

I have a feeling this is related to #4, but perhaps not.

I realize uiBinder is a FakeUiBinder, but I think it should ensure that the mocks it returns do more than just initialize the UiFields, it should also ensure to implement all the original interfaces of the owner widget.

Problems with jdk 1.6

java.lang.UnsupportedClassVersionError: com/google/gwtmockito/GwtMockitoTestRunner : Unsupported major.minor version 51.0

Cannot use with Play 1.2 GWT module and Cobertura

I could not use GWTMockito with Play 1.2's GWT module until I've fixed classpath issues, and unfortunately I couldn't do that by simply extending GwtMockitoTestRunner since that wouldn't let me access it's ClassPool - so I had to take GwtMockitoTestRunner code and make a new class out of it (PlayGwtMockitoTestRunner) with necessary changes:

Also to make Cobertura work a really simple change is needed - returning "net.sourceforge.cobertura" from getPackagesToLoadViaStandardClassloader. I suppose ti can be there by default.

Here's the resulting code. Hope this helps other people who'll try to use GWTMockito and Play 1.2:

package gwt.wdsds2.client.util;

 * This is a modification of com.google.gwtmockito.GwtMockitoTestRunner.
import javassist.CannotCompileException;

/**
 * A JUnit4 test runner that executes a test using GwtMockito. In addition to
 * the standard {@link BlockJUnit4ClassRunner} features, a test executed with {@link GwtMockitoTestRunner} will behave as follows:
 * 
 * <ul>
 * <li>Calls to GWT.create will return mock or fake objects instead of throwing an exception. If a field in the test is annotated with {@link GwtMock}, that
 * field will be returned. Otherwise, if a provider is registered via {@link GwtMockito#useProviderForType}, that provider will be used to create a fake.
 * Otherwise, a new mock instance will be returned. See {@link GwtMockito} for more information and for the set of fake providers registered by default.
 * <li>Final modifiers on methods and classes will be removed. This allows Javascript overlay types like {@link com.google.gwt.dom.client.Element} to be mocked.
 * <li>Native methods will be given no-op implementations so that calls to them don't cause runtime failures. If the native method returns a value, it will
 * return either a default primitive type or a new mock object.
 * <li>The methods of many common widget base classes, such as {@link Widget}, {@link Composite}, and most subclasses of {@link Panel}, will have their methods
 * replaced with no-ops to make it easier to test widgets extending them. This behavior can be customized by overriding
 * {@link GwtMockitoTestRunner#getClassesToStub}.
 * </ul>
 * 
 * @see GwtMockito
 * @author [email protected] (Erik Kuefler)
 */
public class PlayGwtMockitoTestRunner extends BlockJUnit4ClassRunner {

    private final Class<?> unitTestClass;
    private final ClassLoader gwtMockitoClassLoader;
    private final Class<?> customLoadedGwtMockito;

    /**
     * Creates a test runner which allows final GWT classes to be mocked. Works by reloading the test
     * class using a custom classloader and substituting the reference.
     */
    public PlayGwtMockitoTestRunner(Class<?> unitTestClass) throws InitializationError {
        super(unitTestClass);
        this.unitTestClass = unitTestClass;

        // Build a fresh class pool with the system path and any user-specified paths and use it to
        // create the custom classloader
        ClassPool classPool = new ClassPool();
        classPool.appendSystemPath();
        for (String path : getAdditionalClasspaths()) {
            try {
                classPool.appendClassPath(path);
            } catch (NotFoundException e) {
                throw new IllegalStateException("Cannot find classpath entry: " + path, e);
            }
        }
        // !! Play specific classpaths go here
        classPool.appendClassPath(new LoaderClassPath(Enhancer.class.getClassLoader()));
        classPool.appendClassPath(new ApplicationClassesClasspath());
        // End of play specific classpaths

        gwtMockitoClassLoader = new GwtMockitoClassLoader(getParentClassloader(), classPool);

        // Use this custom classloader as the context classloader during the rest of the initialization
        // process so that classes loaded via the context classloader will be compatible with the ones
        // used during test.
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(gwtMockitoClassLoader);

        try {
            // Reload the test class with our own custom class loader that does things like remove
            // final modifiers, allowing GWT Elements to be mocked. Also load GwtMockito itself so we can
            // invoke initMocks on it later.
            Class<?> customLoadedTestClass = gwtMockitoClassLoader.loadClass(unitTestClass.getName());
            customLoadedGwtMockito = gwtMockitoClassLoader.loadClass(GwtMockito.class.getName());

            // Overwrite the private "fTestClass" field in ParentRunner (superclass of
            // BlockJUnit4ClassRunner). This refers to the test class being run, so replace it with our
            // custom-loaded class.
            Field testClassField = ParentRunner.class.getDeclaredField("fTestClass");
            testClassField.setAccessible(true);
            testClassField.set(this, new TestClass(customLoadedTestClass));
        } catch (Exception e) {
            throw new InitializationError(e);
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
    }

    /**
     * Returns a collection of classes whose non-abstract methods should always be replaced with
     * no-ops. By default, this list includes {@link Composite}, {@link DOM} {@link UIObject}, {@link Widget}, and most subclasses of {@link Panel}. It will
     * also include any classes
     * specified via the {@link WithClassesToStub} annotation on the test class. This makes it much
     * safer to test code that uses or extends these types.
     * <p>
     * This list can be customized via {@link WithClassesToStub} or by defining a new test runner extending {@link GwtMockitoTestRunner} and overriding this
     * method. This allows users to explicitly stub out particular classes that are causing problems in tests. If you override this method, you will probably
     * want to retain the classes that are stubbed here by doing something like this:
     * 
     * <pre>
     * &#064;Override
     * protected Collection&lt;Class&lt;?&gt;&gt; getClassesToStub() {
     *     Collection&lt;Class&lt;?&gt;&gt; classes = super.getClassesToStub();
     *     classes.add(MyBaseWidget.class);
     *     return classes;
     * }
     * </pre>
     * 
     * @return a collection of classes whose methods should be stubbed with no-ops while running tests
     */
    protected Collection<Class<?>> getClassesToStub() {
        Collection<Class<?>> classes = new LinkedList<Class<?>>();
        classes.add(Composite.class);
        classes.add(DOM.class);
        classes.add(UIObject.class);
        classes.add(Widget.class);

        classes.add(AbsolutePanel.class);
        classes.add(CellPanel.class);
        classes.add(ComplexPanel.class);
        classes.add(DeckLayoutPanel.class);
        classes.add(DeckPanel.class);
        classes.add(DecoratorPanel.class);
        classes.add(DockLayoutPanel.class);
        classes.add(DockPanel.class);
        classes.add(FlowPanel.class);
        classes.add(FocusPanel.class);
        classes.add(HorizontalPanel.class);
        classes.add(HTMLPanel.class);
        classes.add(LabelBase.class);
        classes.add(LayoutPanel.class);
        classes.add(Panel.class);
        classes.add(PopupPanel.class);
        classes.add(RenderablePanel.class);
        classes.add(ResizeLayoutPanel.class);
        classes.add(SimpleLayoutPanel.class);
        classes.add(SimplePanel.class);
        classes.add(SplitLayoutPanel.class);
        classes.add(StackPanel.class);
        classes.add(VerticalPanel.class);

        WithClassesToStub annotation = unitTestClass.getAnnotation(WithClassesToStub.class);
        if (annotation != null) {
            classes.addAll(Arrays.asList(annotation.value()));
        }

        return classes;
    }

    /**
     * Returns a list of package names that should always be loaded via the standard system
     * classloader instead of through GwtMockito's custom classloader. Any subpackages of these
     * packages will also be loaded with the standard loader. If you're getting
     * "loader constraint violation" errors, try defining a new runner class that overrides this
     * method and adds the package the error is complaining about. If you do this, you will probably
     * want to retain the packages that are blacklisted by default by doing something like this:
     * 
     * <pre>
     * &#064;Override
     * protected Collection&lt;String;&gt; getPackagesToLoadViaStandardClassloader() {
     *   Collection&lt;String&gt; packages = super.getPackagesToLoadViaStandardClassloader();
     *   packages.add("my.package");
     *   return packages;
     * }
     * </pre>
     * 
     * @return a collection of strings such that any class whose fully-qualified name starts with a
     *         string in the collection will always be loaded via the system classloader
     */
    protected Collection<String> getPackagesToLoadViaStandardClassloader() {
        Collection<String> packages = new LinkedList<String>();
        packages.add("com.vladium"); // To support EMMA code coverage tools
        packages.add("net.sourceforge.cobertura"); // To support Cobertura code coverage tools
        packages.add("org.hamcrest"); // Since this package is referenced directly from org.junit
        packages.add("org.junit"); // Make sure the ParentRunner can recognize annotations like @Test
        return packages;
    }

    /**
     * Returns the classloader to use as the parent of GwtMockito's classloader. By default this is
     * the system classloader. This can be customized by defining a custom test runner extending {@link GwtMockitoTestRunner} and overriding this method.
     * 
     * @return classloader to use for delegation when loading classes via GwtMockito
     */
    protected ClassLoader getParentClassloader() {
        // return ClassLoader.getSystemClassLoader();
        return Play.classloader;
    }

    /**
     * Returns a list of additional sources from which the classloader should read while running
     * tests. By default this list is empty; custom sources can be specified by defining a custom test
     * runner extending {@link GwtMockitoTestRunner} and overriding this method.
     * <p>
     * The entries in this list must be paths referencing a directory, jar, or zip file. The entries must not end with a "/". If an entry ends with "/*", then
     * all jars matching the path name are included.
     * 
     * @return a list of strings to be appended to the classpath used when running tests
     * @see ClassPool#appendClassPath(String)
     */
    protected List<String> getAdditionalClasspaths() {
        return new LinkedList<String>();
    }

    /**
     * Runs the tests in this runner, ensuring that the custom GwtMockito classloader is installed as
     * the context classloader.
     */
    @Override
    public void run(RunNotifier notifier) {
        // When running the test, we want to be sure to use our custom classloader as the context
        // classloader. This is important because Mockito will create mocks using the context
        // classloader. Things that can go wrong if this isn't set include not being able to mock
        // package-private classes, since the mock implementation would be created by a different
        // classloader than the class being mocked.
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(gwtMockitoClassLoader);
        try {
            super.run(notifier);
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
    }

    /**
     * Overridden to invoke GwtMockito.initMocks before starting each test.
     */
    @Override
    @SuppressWarnings("deprecation")
    // Currently the only way to support befores
    protected final Statement withBefores(FrameworkMethod method, Object target, Statement statement) {
        try {
            // Invoke initMocks on the version of GwtMockito that was loaded via our custom classloader.
            // This is necessary to ensure that it uses the same set of classes as the unit test class,
            // which we loaded through the custom classloader above.
            customLoadedGwtMockito.getMethod("initMocks", Object.class).invoke(null, target);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return super.withBefores(method, target, statement);
    }

    /** Custom classloader that performs additional modifications to loaded classes. */
    private final class GwtMockitoClassLoader extends Loader implements Translator {

        GwtMockitoClassLoader(ClassLoader classLoader, ClassPool classPool) {
            super(classLoader, classPool);
            try {
                addTranslator(classPool, this);
            } catch (NotFoundException e) {
                throw new AssertionError("Impossible since this.start does not throw");
            } catch (CannotCompileException e) {
                throw new AssertionError("Impossible since this.start does not throw");
            }
        }

        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            // If the class is in a blacklisted package, load it with the default classloader.
            for (String blacklistedPackage : getPackagesToLoadViaStandardClassloader()) {
                if (name.startsWith(blacklistedPackage)) {
                    return PlayGwtMockitoTestRunner.class.getClassLoader().loadClass(name);
                }
            }

            // Otherwise load it with our custom classloader.
            return super.loadClass(name);
        }

        @Override
        public void onLoad(ClassPool pool, String name) throws NotFoundException, CannotCompileException {
            CtClass clazz = pool.get(name);

            // Strip final modifiers from the class and all methods to allow them to be mocked
            clazz.setModifiers(clazz.getModifiers() & ~Modifier.FINAL);
            for (CtMethod method : clazz.getDeclaredMethods()) {
                method.setModifiers(method.getModifiers() & ~Modifier.FINAL);
            }

            // Create stub implementations for certain methods
            for (CtMethod method : clazz.getDeclaredMethods()) {
                if (shouldStubMethod(method)) {
                    method.setModifiers(method.getModifiers() & ~Modifier.NATIVE);
                    CtClass returnType = method.getReturnType();

                    if (typeIs(returnType, String.class)) {
                        method.setBody("return \"\";");
                    } else if (typeIs(returnType, Boolean.class)) {
                        method.setBody(String.format("return Boolean.FALSE;"));
                    } else if (typeIs(returnType, Byte.class)) {
                        method.setBody(String.format("return Byte.valueOf((byte) 0);"));
                    } else if (typeIs(returnType, Character.class)) {
                        method.setBody(String.format("return Character.valueOf((char) 0);"));
                    } else if (typeIs(returnType, Double.class)) {
                        method.setBody(String.format("return Double.valueOf(0.0);"));
                    } else if (typeIs(returnType, Integer.class)) {
                        method.setBody(String.format("return Integer.valueOf(0);"));
                    } else if (typeIs(returnType, Float.class)) {
                        method.setBody(String.format("return Float.valueOf(0f);"));
                    } else if (typeIs(returnType, Long.class)) {
                        method.setBody(String.format("return Long.valueOf(0L);"));
                    } else if (typeIs(returnType, Short.class)) {
                        method.setBody(String.format("return Short.valueOf((short) 0);"));

                    } else if (returnType.isPrimitive()) {
                        method.setBody(null);
                    } else if (returnType.isEnum()) {
                        method.setBody(String.format("return %s.values()[0];", returnType.getName()));

                    } else {
                        // Return mocks for all other methods
                        method.setBody(String.format("return (%1$s) org.mockito.Mockito.mock("
                                + "%1$s.class, new com.google.gwtmockito.impl.ReturnsCustomMocks());", returnType.getName()));
                    }
                }
            }

            // Also stub certain constructors
            for (Class<?> classToStub : getClassesToStub()) {
                if (classToStub.getName().equals(clazz.getName())) {
                    for (CtConstructor constructor : clazz.getConstructors()) {
                        String parameters = makeNullParameters(clazz.getSuperclass().getConstructors()[0].getParameterTypes().length);
                        constructor.setBody("super(" + parameters + ");");
                    }
                }
            }
        }

        private String makeNullParameters(int count) {
            if (count == 0) {
                return "";
            }
            StringBuilder params = new StringBuilder();
            for (int i = 0; i < count; i++) {
                params.append(",null");
            }
            return params.substring(1).toString();
        }

        private boolean typeIs(CtClass type, Class<?> clazz) {
            return type.getName().equals(clazz.getCanonicalName());
        }

        private boolean shouldStubMethod(CtMethod method) {
            // Stub all non-abstract methods of classes for which stubbing has been requested
            for (Class<?> clazz : getClassesToStub()) {
                if (declaringClassIs(method, clazz) && (method.getModifiers() & Modifier.ABSTRACT) == 0) {
                    return true;
                }
            }

            // Always stub native methods
            return (method.getModifiers() & Modifier.NATIVE) != 0;
        }

        private boolean declaringClassIs(CtMethod method, Class<?> clazz) {
            return method.getDeclaringClass().getName().replace('$', '.').equals(clazz.getCanonicalName());
        }

        @Override
        public void start(ClassPool pool) {
        }
    }
}

If a class has a native method, the code coverage will not work properly

If a class has a native method, the code coverage will not work properly.

Steps to reproduce (Eclipse, with actual EclEmma and maven needs to be installed):

  • Import the maven project into eclipse
  • Run "Coverage as -> Junit Testcase" at the class MyWidgetTest
  • The coverage will show Line 63 in MyWidget as covered and miss all other lines.

If I change the native method to non-native, everything works fine.

Maybe there are just problems with line-numbers?

Testet with current version from GIT.

ExceptionInInitializerError when powermock on classpath

I get the following stack trace when running a test with GwtMockitoTestRunner when PowerMock is also on the classpath, even though it is unused:

java.lang.ExceptionInInitializerError
at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.(ConditionalStackTraceFilter.java:17)
at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:30)
at org.mockito.exceptions.base.MockitoException.(MockitoException.java:19)
at org.mockito.exceptions.misusing.MockitoConfigurationException.(MockitoConfigurationException.java:18)
at org.mockito.internal.configuration.ClassPathLoader.loadImplementations(ClassPathLoader.java:145)
at org.mockito.internal.configuration.ClassPathLoader.findPluginImplementation(ClassPathLoader.java:110)
at org.mockito.internal.configuration.ClassPathLoader.findPlatformMockMaker(ClassPathLoader.java:106)
at org.mockito.internal.configuration.ClassPathLoader.(ClassPathLoader.java:59)
at org.mockito.internal.util.MockUtil.(MockUtil.java:21)
at org.mockito.internal.MockitoCore.(MockitoCore.java:40)
at org.mockito.internal.stubbing.defaultanswers.ReturnsMocks.(ReturnsMocks.java:18)
at org.mockito.Answers.(Answers.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at java.lang.Class.getEnumConstantsShared(Class.java:2966)
at java.lang.Class.enumConstantDirectory(Class.java:2987)
at java.lang.Enum.valueOf(Enum.java:231)
at sun.reflect.annotation.AnnotationParser.parseEnumValue(AnnotationParser.java:433)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:298)
at java.lang.reflect.Method.getDefaultValue(Method.java:726)
at sun.reflect.annotation.AnnotationType.(AnnotationType.java:117)
at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:84)
at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:221)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70)
at java.lang.reflect.Field.declaredAnnotations(Field.java:1033)
at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:1026)
at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:196)
at org.junit.runners.model.FrameworkField.getAnnotations(FrameworkField.java:26)
at org.junit.runners.model.TestClass.addToAnnotationLists(TestClass.java:52)
at org.junit.runners.model.TestClass.(TestClass.java:45)
at com.google.gwtmockito.GwtMockitoTestRunner.(GwtMockitoTestRunner.java:133)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.junit.internal.requests.SortingRequest.getRunner(SortingRequest.java:21)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.(JUnit4TestClassReference.java:25)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.NullPointerException
at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.(StackTraceFilter.java:21)
... 53 more

Problem mocking SimplePager

GWT: 2.6.1
GWTMockito: 1.1.4

I try to test my UI class which uses following SimplePager class:

....
    @UiField(provided = true)
    DataGrid<LaboruserValue> dataGrid = new DataGrid<LaboruserValue>(33);

    private final SimplePager dataGridPager = new SimplePager();

....
    // Somewhere in the method I call following: 
    dataGridPager.setDisplay(dataGrid);

In this setDisplay(dataGrid) method I always get following exception:

java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at com.google.gwt.i18n.client.NumberFormat.format(NumberFormat.java:1146)
at com.google.gwt.i18n.client.NumberFormat.format(NumberFormat.java:927)
at com.google.gwt.user.cellview.client.SimplePager.createText(SimplePager.java:566)
at com.google.gwt.user.cellview.client.SimplePager.onRangeOrRowCountChanged(SimplePager.java:573)
at com.google.gwt.user.cellview.client.AbstractPager.setDisplay(AbstractPager.java:137)
at com.google.gwt.user.cellview.client.SimplePager.setDisplay(SimplePager.java:522)
at de.generatio.client.laboruser.Laboruser.initTable(Laboruser.java:268)
at de.generatio.client.laboruser.Laboruser.(Laboruser.java:125)
at de.generatio.client.laboruser.LaboruserTest.setUp(LaboruserTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:301)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Any ideas?

Thanks,
Lofi

Using a FakeProvider for RPC services

I read through issue #6 and I can see where you addressed some of his issues. The problem I'm having is I want to use a FakeProvider for an RPC interface. Looking at GwtMockito.Bridge.create, it seems to be attempting to match an Async class name before checking the list of registeredProviders.

As bwolff mentioned, this means activities' RPC service members must be accessible and non-final, which I'd rather not do.

Thanks for everything,
Andrew

getClassesToStub via annotation

Hi,

since overriding the getClassesToStub method could be quite common for certain types of widgets, creating a custom runner could become nasty.

Therefore I suggest an additional annotation on the TestClass where one or more classes to stub could be specified. This is done similiarly with the PrepareForTest annotation in PowerMockito.

Best,
Daniel

Memory Leak in GwtMockitoTestRunner$GwtMockitoClassLoader

When running a large suite of JUnit test classes using the @GwtMockitoTestRunner, we consistently encounter a "java/lang/OutOfMemoryError".

We used the Eclipse Memory Analyzer to inspect the resulting heap dump file.
The analysis identified the problem suspect as:
273 instances of "com.google.gwtmockito.GwtMockitoTestRunner$GwtMockitoClassLoader", loaded by "com.ibm.oti.vm.BootstrapClassLoader @ 0x8004b120" occupy 1,519,903,320 (94.34%) bytes.

We are running the following versions of the related libraries:
JUnit - junit:junit:4.12
Mockito - org.mockito:mockito-all:1.10.19
GWTMockito - com.google.gwt.gwtmockito:gwtmockito:1.1.5

To run the tests, we are simply annotating our test classes with
@RunWith(GwtMockitoTestRunner.class)

Is there something we need to do in a tearDown() method to make sure the GwtMockitoTestRunner releases the gwtMockitoClassLoader it created?

"java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$$EnhancerByMockitoWithCGLIB$$29edae7f cannot be cast to com.google.gwt.user.client.Element" while trying to test a widget extending SimpleLayoutPanel

Let's take the following example:

public class MyPanel extends SimpleLayoutPanel {

    private Label label;

    public MyPanel() {
        label = GWT.create(Label.class);
        label.setText("It's my panel");

        add(label);
    }

}

And a test case:

@RunWith(GwtMockitoTestRunner.class)
public class MyPanelTests {

    private MyPanel myPanel;

    @Before
    public void setUp() {
        myPanel = new MyPanel();
    }

    @Test
    public void testTruth() {
        assertTrue(true);
    }
}

Running this test case will result in the following exception:

java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$$EnhancerByMockitoWithCGLIB$$bd5b9f31 cannot be cast to com.google.gwt.user.client.Element
    at com.google.gwt.user.client.DOM.createDiv(DOM.java:149)
    at com.google.gwt.user.client.ui.SimplePanel.<init>(SimplePanel.java:35)
    at com.google.gwt.user.client.ui.SimpleLayoutPanel.<init>(SimpleLayoutPanel.java:31)
    at cern.ais.plugin.gwt.client.layout.view.MyPanel.<init>(MyPanel.java:11)
    at cern.ais.plugin.gwt.client.layout.view.MyPanelTests.setUp(MyPanelTests.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:102)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:24)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:77)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

If MyPanel extends Composite, everything works fine, but with SimpleLayoutPanel (or just SimplePanel) the result is the same as the one above.

Is this a known limitation?

In many cases widgets can be refactored to extend Composite, but is there a way of testing with gwtmockito those that have to extend something else than Composite, or is using GWTTestCase required in such cases?

Thoughts on a 1.1.3 release?

It looks like there have been some very handy commits since 1.1.2, in particular the fix to work with org.hamcrest. Any thoughts on a 1.1.3 release?

Thanks!!

cannot use com.google.gwt.user.datepicker.client.DatePicker

I am using gwtmockito 1.1.5

java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$$EnhancerByMockitoWithCGLIB$$c39d8300 cannot be cast to com.google.gwt.dom.client.Element
at com.google.gwt.user.client.ui.HTMLTable$CellFormatter.getCellElement(HTMLTable.java:428)
at com.google.gwt.user.client.ui.HTMLTable$CellFormatter.getRawElement(HTMLTable.java:441)
at com.google.gwt.user.client.ui.HTMLTable$CellFormatter.access$400(HTMLTable.java:161)
at com.google.gwt.user.client.ui.HTMLTable.cleanCell(HTMLTable.java:1578)
at com.google.gwt.user.client.ui.HTMLTable.setText(HTMLTable.java:1175)
at com.google.gwt.user.datepicker.client.DefaultCalendarView.setup(DefaultCalendarView.java:249)
at com.google.gwt.user.datepicker.client.DatePicker.(DatePicker.java:306)
at com.google.gwt.user.datepicker.client.DatePicker.(DatePicker.java:285)
at com.kf.amplifire.modules.widgets.KfDatePickerCellTest.testImaMonkey(KfDatePickerCellTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at com.google.gwtmockito.GwtMockitoTestRunner.run(GwtMockitoTestRunner.java:301)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

My test class looks like this:
package com.a.bc.modules.widgets;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;

import com.google.gwt.user.datepicker.client.DatePicker;
import com.google.gwtmockito.GwtMockitoTestRunner;

@RunWith(GwtMockitoTestRunner.class)
public class KfDatePickerCellTest {

@test
public void testDatePicker() {

  DatePicker nosePicker = new DatePicker();
  assertTrue(nosePicker != null);

}

}

Mocked com.google.gwt.i18n.client.DateTimeFormatInfo in com.google.gwt.i18n.shared.DateTimeFormat return nothing on ampms() method call

Hi!
I'm trying to set up my test cases with GWT Mockito but I'm encountering issues with GWT date formatting :
when calling DateTimeFormat formatter = DateTimeFormat.getFormat(format); with format "MM/dd/yyyy h:mm a" and then trying to parse the date 'Tue Jan 04 12:25:00 CET 2011' we are getting the following Exception:
java.lang.ArrayIndexOutOfBoundsException: 1
at com.google.gwt.i18n.shared.DateTimeFormat.formatAmPm(DateTimeFormat.java:1032)
at com.google.gwt.i18n.shared.DateTimeFormat.subFormat(DateTimeFormat.java:1760)
at com.google.gwt.i18n.shared.DateTimeFormat.format(DateTimeFormat.java:810)
at com.google.gwt.i18n.shared.DateTimeFormat.format(DateTimeFormat.java:746)

Is this a bug or is there a way to control the behaviour of the injected DateTimeFormatInfo (which is a mock injected by GWTMockito I suppose)

Thanks !

gwtmockito-sample module is not compiling in the 1.0.1-SNAPSHOT

Hello! I've tried to build the snapshot 1.0.1 with latest fixes and the gwtmockito-sample failed to compile with folowing errors:
/home/voila/Workspace/Projects/mockito/gwtmockito-sample/src/test/java/sample/MyWidgetTestWithoutRunner.java:[87,78] <anonymous sample.MyWidgetTestWithoutRunner$2> is not abstract and does not override abstract method getFake(java.lang.Class<?>) in com.google.gwtmockito.fakes.FakeProvider /home/voila/Workspace/Projects/mockito/gwtmockito-sample/src/test/java/sample/MyWidgetTestWithoutRunner.java:[89,22] name clash: getFake(java.lang.Class<? extends com.google.gwt.user.client.ui.HasText>) in <anonymous sample.MyWidgetTestWithoutRunner$2> and getFake(java.lang.Class<?>) in com.google.gwtmockito.fakes.FakeProvider have the same erasure, yet neither overrides the other /home/voila/Workspace/Projects/mockito/gwtmockito-sample/src/test/java/sample/MyWidgetTestWithoutRunner.java:[88,7] method does not override or implement a method from a supertype /home/voila/Workspace/Projects/mockito/gwtmockito-sample/src/test/java/sample/MyWidgetTest.java:[73,78] <anonymous sample.MyWidgetTest$1> is not abstract and does not override abstract method getFake(java.lang.Class<?>) in com.google.gwtmockito.fakes.FakeProvider /home/voila/Workspace/Projects/mockito/gwtmockito-sample/src/test/java/sample/MyWidgetTest.java:[75,22] name clash: getFake(java.lang.Class<? extends com.google.gwt.user.client.ui.HasText>) in <anonymous sample.MyWidgetTest$1> and getFake(java.lang.Class<?>) in com.google.gwtmockito.fakes.FakeProvider have the same erasure, yet neither overrides the other /home/voila/Workspace/Projects/mockito/gwtmockito-sample/src/test/java/sample/MyWidgetTest.java:[74,7] method does not override or implement a method from a supertype

The change Class to Class in anonymous FakeProvides fixes the issue.

Explicit cast issue

Hi!
I've found the issue which is the case in GXT 3.0.1 . Let me introduce the failing method:

  private void ensureFocusElement() {
    if (focusEl != null) {
      focusEl.removeFromParent();
    }
    focusEl = (XElement) getElement().appendChild(focusImpl.createFocusable());
    focusEl.addClassName(CommonStyles.get().noFocusOutline());
    if (focusEl.hasChildNodes()) {
      focusEl.getFirstChildElement().addClassName(CommonStyles.get().noFocusOutline());
      com.google.gwt.dom.client.Style focusElStyle = focusEl.getFirstChildElement().getStyle();
      focusElStyle.setBorderWidth(0, Unit.PX);
      focusElStyle.setFontSize(1, Unit.PX);
      focusElStyle.setPropertyPx("lineHeight", 1);
    }
    focusEl.setLeft(0);
    focusEl.setTop(0);
    focusEl.makePositionable(true);
    focusEl.addEventsSunk(Event.FOCUSEVENTS);

  }

The test failing with:
java.lang.ClassCastException: com.google.gwt.dom.client.Node$$EnhancerByMockitoWithCGLIB$$2aac32b3 cannot be cast to com.sencha.gxt.core.client.dom.XElement
Well, make sence , since appendChild returns mocked Node implementation.
How can i workaround it? This object created with new operator and we can't create mock (with @GwtMock) for it.

Thanks.

GWTMockito does not work with new JUnit 4.12

JUnit 4.11 org.junit.runners.ParentRunner:
private final TestClass fTestClass;

JUnit 4.12 org.junit.runners.ParentRunner:
private final TestClass testClass;

java.lang.NoSuchFieldException: fTestClass
  at java.lang.Class.getDeclaredField(Unknown Source)
  at com.google.gwtmockito.GwtMockitoTestRunner.(GwtMockitoTestRunner.java:146)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
  at java.lang.reflect.Constructor.newInstance(Unknown Source)
  at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
  at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
  at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
  at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
  at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
  at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:33)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.(JUnit4TestClassReference.java:25)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

ClassCastException with JsArrayInteger

Caused by: java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$$EnhancerByMockitoWithCGLIB$$ab2112c9 cannot be cast to com.google.gwt.core.client.JsArrayInteger
at com.google.gwt.user.cellview.client.HasDataPresenter.resolvePendingState(HasDataPresenter.java:1112)
at com.google.gwt.user.cellview.client.HasDataPresenter.flush(HasDataPresenter.java:518)
at com.google.gwt.user.cellview.client.AbstractCellTable.flush(AbstractCellTable.java:1050)

GwtMockitoClassLoader overrides wrong loadClass method and so does not delegate classes to parent correctly

GwtMockitoClassLoader (in GwtMockitoTestRunner) overrides loadClass(String) but in order to intercept all attempts to load a class it should override loadClass(String, boolean) that is called from a child ClassLoader.

This issue was found when using Mockito to mock a class (not interface). It added org.mockito to the packages to load from the standard ClassLoader. The test failed with the following error:

Caused by: java.lang.IllegalAccessError: tried to access class org.mockito.cglib.core.ReflectUtils$1 from class org.mockito.cglib.core.ReflectUtils
        at org.mockito.cglib.core.ReflectUtils.<clinit>(ReflectUtils.java:41)
        at .....$$EnhancerByMockitoWithCGLIB$$ba9e6813.CGLIB$STATICHOOK1(<generated>)
        at .....$$EnhancerByMockitoWithCGLIB$$ba9e6813.<clinit>(<generated>)
        at sun.reflect.GeneratedSerializationConstructorAccessor1.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:56)
        at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
        at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128)
        at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63)
        at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
        at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
        at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
        at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
        at org.mockito.Mockito.mock(Mockito.java:1243)
        at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:30)
        at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
        at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43)
        at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66)
        at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71)
        at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
        at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
        at com.google.gwtmockito.GwtMockito.initMocks(GwtMockito.java:128)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.