{"id":21444876,"url":"https://github.com/google/gwtmockito","last_synced_at":"2025-07-14T18:31:53.561Z","repository":{"id":8358399,"uuid":"9922054","full_name":"google/gwtmockito","owner":"google","description":"Better GWT unit testing","archived":false,"fork":false,"pushed_at":"2024-02-06T19:38:15.000Z","size":406,"stargazers_count":157,"open_issues_count":23,"forks_count":50,"subscribers_count":22,"default_branch":"master","last_synced_at":"2024-05-08T21:50:06.811Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://google.github.io/gwtmockito","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/google.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-05-07T21:27:35.000Z","updated_at":"2024-04-24T15:31:25.000Z","dependencies_parsed_at":"2022-08-07T04:00:30.353Z","dependency_job_id":null,"html_url":"https://github.com/google/gwtmockito","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgwtmockito","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgwtmockito/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgwtmockito/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgwtmockito/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/google","download_url":"https://codeload.github.com/google/gwtmockito/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225991824,"owners_count":17556370,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-23T02:22:07.592Z","updated_at":"2024-11-23T02:22:14.921Z","avatar_url":"https://github.com/google.png","language":"Java","funding_links":[],"categories":["Testing","测试"],"sub_categories":[],"readme":"## What is GwtMockito?\n\nTesting GWT applications using `GWTTestCase` can be a pain - it's slower than\nusing pure Java tests, and you can't use reflection-based tools like mocking\nframeworks. But if you've tried to test widgets using normal test cases, you've\nprobably run into this error:\n\n    ERROR: GWT.create() is only usable in client code!  It cannot be called,\n    for example, from server code. If you are running a unit test, check that \n    your test case extends GWTTestCase and that GWT.create() is not called\n    from within an initializer or constructor.\n\nGwtMockito solves this and other GWT-related testing problems by allowing you\nto call GWT.create from JUnit tests, returning [Mockito][1] mocks.\n\n## How do I use it?\n\nGetting started with GwtMockito using Junit 4.5+ is easy. Just annotate your test\nwith `@RunWith(GwtMockitoTestRunner.class)`, then any calls to `GWT.create`\nencountered will return Mockito mocks instead of throwing exceptions:\n\n```java\n@RunWith(GwtMockitoTestRunner.class)\npublic class MyTest {\n  @Test\n  public void shouldReturnMocksFromGwtCreate() {\n    Label myLabel = GWT.create(Label.class);\n    when(myLabel.getText()).thenReturn(\"some text\");\n    assertEquals(\"some text\", myLabel.getText());\n  }\n}\n```\n\nGwtMockito also creates fake implementations of all UiBinders that automatically\npopulate `@UiField`s with Mockito mocks. Suppose you have a widget that looks\nlike this:\n\n```java\npublic class MyWidget extends Composite {\n  interface MyUiBinder extends UiBinder\u003cWidget, MyWidget\u003e {}\n  private final MyUiBinder uiBinder = GWT.create(MyUiBinder.class);\n\n  @UiField Label numberLabel;\n  private final NumberFormatter formatter;\n\n  public MyWidget(NumberFormatter formatter) {\n    this.formatter = formatter;\n    initWidget(uiBinder.createAndBindUi(this);\n  }\n\n  void setNumber(int number) {\n    numberLabel.setText(formatter.format(number));\n  }\n}\n```\n\nWhen `createAndBindUi` is called, GwtMockito will automatically populate \n`numberLabel` with a mock object. Since `@UiField`s are package-visible, they \ncan be read from your unit tests, which lets you test this widget as follows:\n\n```java\n@RunWith(GwtMockitoTestRunner.class)\npublic class MyWidgetTest {\n\n  @Mock NumberFormatter formatter;\n  private MyWidget widget;\n\n  @Before\n  public void setUp() {\n    widget = new MyWidget(formatter);\n  }\n\n  @Test\n  public void shouldFormatNumber() {\n    when(formatter.format(5)).thenReturn(\"5.00\");\n    widget.setNumber(5);\n    verify(widget.numberLabel).setText(\"5.00\");\n  }\n}\n```\n\nNote that GwtMockito supports the `@Mock` annotation from Mockito, allowing \nstandard Mockito mocks to be mixed with mocks created by GwtMockito.\n\nThat's all you need to know to get started - read on if you're interested in\nhearing about some advanced features.\n\n### Accessing the mock returned from GWT.create\n\nReturning mocks from `GWT.create` isn't very useful if you don't have any way to\nverify or set behaviors on them. You can do this by annotating a field in your \ntest with `@GwtMock` - this will cause all calls to `GWT.create` for that type\nto return a mock stored in that field, allowing you to reference it in your\ntest. So if you have a class that looks like\n\n```java\npublic class MyClass {\n  public MyClass() {\n    SomeInterface myInterface = GWT.create(SomeInterface.class);\n    myInterface.setSomething(true);\n  }\n}\n```\n\nthen you can verify that it works correctly by writing a test that looks like\nthis:\n\n```java\n@RunWith(GwtMockitoTestRunner.class)\npublic class MyClassTest {\n  @GwtMock SomeInterface mockInterface;\n\n  @Test\n  public void constructorShouldSetSomething() {\n    new MyClass();\n    verify(mockInterface).setSomething(true);\n  }\n}\n```\n\n### Returning fake objects\n\nBy default, GwtMockito will return fake implementations (which don't require you\nto specify mock behavior) for any classes extending the following types:\n\n  * UiBinder\n  * ClientBundle\n  * Messages\n  * CssResource\n  * SafeHtmlTemplates\n\nYou can add fakes for additional types by invoking \n`GwtMockito.useProviderForType(Class, FakeProvider)` in your `setUp` method. \nThis will cause all calls to `GWT.create` for the given class or its subclasses\nto invoke the given `FakeProvider` to determine what to return. See the\n[javadoc reference][2] for more details.\n\n### Mocking final classes and methods\n\nMockito does not normally allow final classes and methods to be mocked. This \nposes problems in GWT since [JavaScript overlay types][3] (which include \n`Element` and its subclasses) require all methods to be final. Fortunately,\nGwtMockito does some classloader black magic to remove all final modifiers from\nclasses and interfaces, so the following test will pass:\n\n```java\n@RunWith(GwtMockitoTestRunner.class)\npublic class MyTest {\n  @Mock Element element;\n\n  @Test\n  public void shouldReturnMocksFromGwtCreate() {\n    when(element.getClassName()).thenReturn(\"mockClass\");\n    assertEquals(\"mockClass\", myLabel.getClassName());\n  }\n}\n```\n\nAs long as your test uses `GwtMockitoTestRunner`, it is possible to mock any\nfinal methods.\n\n### Dealing with native methods\n\nUnder normal circumstances, JUnit tests will fail with an `UnsatisfiedLinkError` when encountering a native JSNI method. GwtMockito works around this problem\nusing more classloader black magic to provide no-op implementations for all\nnative methods using the following rules:\n\n  * `void` methods do nothing.\n  * Methods returning primitive types return the default value for that type (0,\n    false, etc.)\n  * Methods returning `String`s return the empty string.\n  * Methods returning other objects return a mock of that object configured with\n    `RETURNS_MOCKS`.\n\nThese rules allow many tests to continue to work even when calling incindental\nnative methods. Note that this can be dangerous - a JSNI method that normally\nalways returns `true` would always return `false` when stubbed by GwtMockito.\nAs much as possible, you should isolate code that depends on JSNI into its own\nclass, [inject][4] that class into yours, and test the factored-out class using\n`GWTTestCase`.\n\n### Support for JUnit 3 and other tests that can't use custom runners\n\nThough `GwtMockitoTestRunner` is the easiest way to use GwtMockito, it won't\nwork if you're using JUnit 3 or rely on another custom test runner. In these\nsituations, you can still get most of the benefit of GwtMockito by calling\n`GwtMockito.initMocks` directly. A test written in this style looks like this:\n\n```java\npublic class MyWidgetTest extends TestCase {\n\n  private MyWidget widget;\n\n  @Override\n  public void setUp() {\n    super.setUp();\n    GwtMockito.initMocks(this);\n    widget = new MyWidget() {\n      protected void initWidget(Widget w) {\n        // Disarm for testing\n      }\n    };\n  }\n\n  @Override\n  public void tearDown() {\n    super.tearDown();\n    GwtMockito.tearDown();\n  }\n\n  public void testSomething() {\n    // Test code goes here\n  }\n}\n```\n\nThe test must explicitly call `initMocks` during its setup and `tearDown` when\nit is being teared down, or else state can leak between tests. When \ninstantiating a widget, the test must also subclass it and override initWidget\nwith a no-op implementation, or else it will fail when this method attempts to\ncall Javascript. Note that when testing in this way the features described in\n\"Mocking final classes and methods\" and \"Dealing with native methods\" won't\nwork - there is no way to mock final methods or automatically replace native\nmethods without using `GwtMockitoTestRunner`.\n\n## How do I install it?\nIf you're using Maven, you can add the following to your `\u003cdependencies\u003e`\nsection:\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.google.gwt.gwtmockito\u003c/groupId\u003e\n  \u003cartifactId\u003egwtmockito\u003c/artifactId\u003e\n  \u003cversion\u003e1.1.9\u003c/version\u003e\n  \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nYou can also download the [jar][5] directly or check out the source using git\nfrom \u003chttps://github.com/google/gwtmockito.git\u003e. In these cases you will have\nto manually install the jars for [Mockito][6] and [Javassist][7].\n\n## Where can I learn more?\n  * For more details on the GwtMockito API, consult the [Javadoc][8]\n  * For an example of using GwtMockito to test some example classes, see the\n    [sample app][9].\n\n## Version history\n\n### 1.1.9\n  * Support ResourcePrototype methods in fake CLientBundles. (Thanks to zbynek)\n  * Add a `@WithExperimentalGarbageCollection` annotation. (Thanks to LudoP)\n  * Updated javassist dependency. (Thanks to TimvdLippe)\n\n### 1.1.8\n  * Preliminary Java 9 support. (Thanks to benoitf)\n\n### 1.1.7\n  * Update GWT to version 2.8.0.\n  * Update Javassist to version 3.22.\n  * Stubbing for ValueListBox. (Thanks to jschmied)\n  * Stubbing for URL encoding. (Thanks to jschmeid)\n  * Generate hashCode and equals for Messages. (Thanks to zolv)\n\n### 1.1.6\n  * Improved support for running tests in IntelliJ.\n  * Fix for stubbing DatePicker.\n  * Better support for non-default classloaders. (Thanks to leanseefeld)\n  * Depend on mockito-core instead of mockito-all. (Thanks to psiroky)\n\n### 1.1.5\n  * Support for JUnit 4.12. (Thanks to selesse)\n  * Provide a better error message for `ClassCastException`s that we can't work around.\n  * Support for JaCoCo. (Thanks to rsauciuc)\n  * Include a fake implementation of `NumberConstants`.\n  * Fixed support for `History` methods.\n  * Fix for some `TextBox` methods.\n  * Fix instantiation of checkboxes and radio buttons.\n\n### 1.1.4\n  * Many fixes for `ClassCastException`s when mocking various classes.\n  * Support for Cobertura coverage tools. (Thanks to mvmn)\n  * Try to intelligently return the right value for getTagName when possible.\n  * Fixed a classloader delegation issue. (Thanks to paulduffin)\n  * Add an annotation allowing the excludelist of classes that are always\n    loaded via the standard classloader to be specified on a per-test bases.\n\n### 1.1.3\n  * Support for Hamcrest matchers.\n  * Added a method to specify packages that should never be reloaded.\n  * Added a getFake method to provide direct access to registered fakes.\n  * Fixed assertion errors in classes extending LabelBase.\n  * Added an annotation allowing stubbed classes to be specified on a\n    per-test basis (suggested by danielkaneider)\n  * Support for GWT 2.6.\n  * Fix to allow FakeProviders to be specified for RPC interfaces.\n\n### 1.1.2\n  * Fix for UiBinders that generate parameterized widgets.\n  * Fix to always use the most specific provider available when multiple\n    providers could provide a type. (Thanks to reimai)\n  * Compatability with EMMA code coverage tools.\n\n### 1.1.1\n  * Fix for a bug in `AsyncAnswers`. (Thanks to tinamou)\n  * Mock `@GwtMock` fields in superclasses the same way that Mockito does.\n    (Thanks to justinmk)\n  * Fix for a conflict with PowerMock.\n\n### 1.1.0\n  * Support for GWT-RPC by returning mock async interfaces when GWT.creating\n    the synchronous interface\n  * Support for testing widgets that expand Panel classes by automatically\n    stubbing Panel methods.\n  * Ability to customize classes that are automatically stubbed in order to\n    support widgets extending third-party base classes.\n  * Ability to customize the classloader and classpath used by GwtMockito for\n    better tool integration.\n  * More flexible FakeProviders that allow the returned type to be unrelated\n    to the input type. **Note that this can be a breaking change in some\n    cases: `getFake` should now just take a `Class\u003c?\u003e` instsead of a \n    `Class\u003c? extends T\u003e`**. See [here][10] for an example.\n\n### 1.0.0\n  * Initial release\n\n[1]: https://code.google.com/p/mockito/\n[2]: https://static.javadoc.io/com.google.gwt.gwtmockito/gwtmockito/1.1.8/com/google/gwtmockito/GwtMockito.html#useProviderForType-java.lang.Class-com.google.gwtmockito.fakes.FakeProvider-\n[3]: https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsOverlay\n[4]: https://en.wikipedia.org/wiki/Dependency_injection\n[5]: https://search.maven.org/remotecontent?filepath=com/google/gwt/gwtmockito/gwtmockito/1.1.8/gwtmockito-1.1.8.jar\n[6]: https://code.google.com/p/mockito/downloads/list\n[7]: http://www.jboss.org/javassist/downloads\n[8]: https://www.javadoc.io/doc/com.google.gwt.gwtmockito/gwtmockito/1.1.8\n[9]: https://github.com/google/gwtmockito/tree/master/gwtmockito-sample/src\n[10]: https://github.com/google/gwtmockito/commit/52b5ddfc08df1b630cd1f241d2afaa08fed82a77\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2Fgwtmockito","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogle%2Fgwtmockito","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2Fgwtmockito/lists"}