[
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "content": "Hey there and thank you for using PowerMock\n\nPlease read the following tips before filing an issue:\n\nIs this something you can debug and fix?\n-------------------------------------------------------\n\nCan you see anything in the logs? Can you debug why this happens? **Send a pull request**! Bug fixes and documentation fixes are very welcome.\n\n\nIs this question about PowerMock usage?\n---------------------------------------\n\nThe better way to ask question:\n\n* The PowerMock [mailing-list](https://groups.google.com/forum/#!forum/powermock/)\n* [Stackoverflow](http://stackoverflow.com/questions/tagged/powermock) with the tag 'powermock'. (Make sure you **include a short code snippet to demonstrate the problem** and if you have an exception then make sure **include stack trace**.)\n\nNone of the above, want to create a GitHub issue\n------------------------------------------------------------------\n\nIssues should always have a [Short, Self Contained, Correct (Compilable)](http://sscce.org), Example (same as any question on stackoverflow.com)\n\nIn order to help us to clarify issue can you answer the following question:\n\nWhat steps will reproduce the problem?\nWhat is the expected output?\nWhat do you see instead?\nWhat version of the product are you using? "
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: \"gradle\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n"
  },
  {
    "path": ".github/workflows/gradle-wrapper-validation.yml",
    "content": "name: \"Validate Gradle Wrapper\"\non: [push, pull_request]\n\njobs:\n  validation:\n    name: \"Gradle wrapper validation\"\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: gradle/wrapper-validation-action@v1\n"
  },
  {
    "path": ".gitignore",
    "content": "target\n*.iws\n*.ipr\n*.iml\n.classpath\n.project\n.settings\n.springBeans\nrepo\n.idea\n**/build/**\n.gradle\n**/out/**\n**/classes/**\n**/bin/**"
  },
  {
    "path": ".travis.yml",
    "content": "# More details on how to configure the Travis build\n# https://docs.travis-ci.com/user/customizing-the-build/\n\n# Speed up build by leveraging travis caches\ncache:\n  directories:\n    - $HOME/.gradle/caches/\n    - $HOME/.gradle/wrapper/\n\n# Note that OracleJDK 9 is available for jdk_switcher only on Trusty.\n# https://github.com/travis-ci/travis-ci/issues/7253#issuecomment-283671037\ndist: trusty\n\ngroup: edge\n\nlanguage: java\n\nmatrix:\n  include:\n  - jdk: oraclejdk8\n    env:\n      - SKIP_RELEASE=true\n      - powermock.byte-code-framework=Javassist\n  - jdk: oraclejdk9\n    env:\n      - SKIP_RELEASE=true\n      - powermock.byte-code-framework=Javassist\n  - jdk: oraclejdk8\n\n#Below skips the installation step completely (https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step)\n#We need it because otherwise Travis CI injects an awkward './gradlew assemble' step into the CI workflow\n#We want to control and decide what Gradle tasks are executed\ninstall:\n - true\n\nscript:\n  # We are using && below on purpose\n  # ciPerformRelease must run only when the entire build has completed\n  # This guarantees that no release steps are executed when the build or tests fail\n  - ./gradlew assemble -s -PcheckJava6Compatibility && ./gradlew -i -s check && ./gradlew -i ciPerformRelease\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to PowerMock #\n\nFirst of all, thank you for considering contributing to PowerMock. Please, read the guideline before start. Following these guidelines helps to communicate that you respect the time of the developers managing and developing PowerMock.\n\n## Content ##\n\n* [If looking for support](#if-looking-for-support)\n* [Pull request criteria](#pull-request-criteria)\n* [General info](#general-info)\n* [More on pull requests](#more-on-pull-requests)\n\n\n## If looking for support ##\n\nSearch / Ask question on [stackoverflow](https://stackoverflow.com/questions/tagged/powermock)\nGo to the PowerMock  [mailing-list](https://groups.google.com/forum/#!forum/powermock/) (moderated)\nIssues should always have a [Short, Self Contained, Correct (Compilable)](http://sscce.org), Example (same as any question on stackoverflow.com)\n\n## Pull request criteria ##\n* At least one commit message in the PR starts with Fixes #id : where id is an [issue tracker](https://github.com/powermock/powermock/issues) id. This allows track release notes. Also GitHub will track the issue and [close it](https://github.com/blog/1386-closing-issues-via-commit-messages) when the PR is merged.\n\n* Use `@since` tags for new public APIs\n\n* Include tests\n\n* Document public APIs with examples\n\n* PowerMock provides two APIs: EasyMock and Mockito. If you add a new feature, please follow the same API style as the mocking framework which API you extend.\n\n* For new features consider adding new documentation item in `PowerMock`/`PowerMockito` class. \n\n* Also, look at the [GitHub's Pull Request guide](https://github.com/blog/1943-how-to-write-the-perfect-pull-request)\n\n## General info ##\n* Comment on issues or pull requests\n\n* If you know the answer to a question posted to our mailing list - don't hesitate to write a reply. That helps us a lot.\n\n* Also, don't hesitate to ask questions on the mailing list - that helps us improve javadocs/FAQ.\n\n* Please suggest changes to javadoc/exception messages when you find something unclear.\n\n* If you miss a particular feature in PowerMock - browse or ask on the mailing list, show us a sample code and describe the problem.\n\n*  Wondering what to work on? See task/bug labeled with [\"for new contributors\"](https://github.com/powermock/powermock/issues?q=is%3Aopen+is%3Aissue+label%3A%22for+new+contributors%22). Remember that some feature requests we somewhat not agree with so not everything we want to work on.\n\n*  PowerMock currently uses GitHub for deployment, so you can create a fork of PowerMock. Go to the github project and \"Create your own fork\". Create a new branch, commit, ..., when you're ready raise a your pull request.\n\n*  Note the project now uses gradle, when your Gradle install is ready, make your IDE project's files (for example gradle idea). Other gradle commands are listed via gradle tasks.\n\n## More on pull requests ##\n\n* On pull requests, please document the change, what it brings, what is the benefit.\n\n* **Clean commit history** in the topic branch in your fork of the repository, even during review. That means that commits are _rebased_ and _squashed_ if necessary, so that each commit clearly changes one things and there are no extraneous fix-ups.\n\n  For that matter it's possible to commit [_semantic_ changes](http://lemike-de.tumblr.com/post/79041908218/semantic-commits). _Tests are an asset, so is history_.\n\n  _Exemple gratia_:\n```\nFixes #777 : The new feature\nFixes #777 : Refactors this part of PowerMock to make feature possible\n```\n\n* In the code, always test your feature / change, in unit tests and in our acceptance test suite located in [tests](https://github.com/powermock/powermock/tree/master/tests) module. Older tests will be migrated when a test is modified.\n\n* New test methods should follow a snake case convention (`ensure_that_stuff_is_doing_that`), this allows the test name to be fully expressive on intent while still readable.\n\n* Documentation !!! Always document the public API with love. Internals could use some love too but it's argubly not as important. In all cases the code should _auto-document_ itself like any [well designed API](rebased and squashed if necessary, so that each commit clearly changes one things and there are no extraneous fix-ups).\n\n* We use (4) spaces instead of tabs. Make sure line ending is Unix style (LF). More on line ending on the [Github help](https://help.github.com/articles/dealing-with-line-endings/).\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2007-2017 PowerMock Contributors\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "![PowerMock](powermock.png)\n\n[![Build Status](https://travis-ci.org/powermock/powermock.svg?branch=master)](https://travis-ci.org/powermock/powermock)\n[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.powermock/powermock-core/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.powermock/powermock-core)\n[ ![Download](https://api.bintray.com/packages/powermock/maven/powermock/images/download.svg) ](https://bintray.com/powermock/maven/powermock/_latestVersion)\n[![Javadoc](https://javadoc-emblem.rhcloud.com/doc/org.powermock/powermock-core/badge.svg)](http://www.javadoc.io/doc/org.powermock/powermock-core)\n\nWriting unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to good design, but this is not always the case. For example final classes and methods cannot be used, private methods sometimes need to be protected or unnecessarily moved to a collaborator, static methods should be avoided completely and so on simply because of the limitations of existing frameworks.\n\nPowerMock is a framework that extends other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more. By using a custom classloader no changes need to be done to the IDE or continuous integration servers which simplifies adoption. Developers familiar with the supported mock frameworks will find PowerMock easy to use, since the entire expectation API is the same, both for static methods and constructors. PowerMock aims to extend the existing API's with a small number of methods and annotations to enable the extra features. Currently PowerMock supports EasyMock and Mockito.\n\nWhen writing unit tests it is often useful to bypass encapsulation and therefore PowerMock includes several features that simplifies reflection specifically useful for testing. This allows easy access to internal state, but also simplifies partial and private mocking.\n\nPlease note that PowerMock is mainly intended for people with expert knowledge in unit testing. Putting it in the hands of junior developers may cause more harm than good.\n\n## News\n* 2019-04-21: PowerMock 2.0.2 has been released and is avaliable in Maven Central. The release includes fixes for [issue](https://github.com/powermock/powermock/issues/979) with PowerMock JavaAgent and the latest JDK and a [security issue](https://github.com/powermock/powermock/issues/973) with the build script. \n* 2019-01-07: PowerMock 2.0.0 has been released. Main changes: offical supporting Mockito 2.x and dropping supporting Mockito 1.x. This release also supports Java 9. Other change read in [release notes](https://github.com/powermock/powermock/releases/tag/powermock-2.0.0). \n* 2017-08-12: PowerMock 1.7.1 has been released with one, but significant change: the old API for verifying static mock has been deprecated and a new one has been added. Old API will be removed in version PowerMock 2.0 due to incompatibility with Mockito Public API.\n* 2017-06-16: PowerMock 1.7.0 has been released with support for Mockito 2 (not only beta versions) and new features such as global `@PowerMockIgnore` as well as bug fixes and other improvements. See [release notes](https://github.com/powermock/powermock/releases/tag/powermock-1.7.0) and [change log](https://raw.githubusercontent.com/powermock/powermock/master/docs/changelog.txt) for details. \n* 2017-02-03: Johan blogs about how to mock slf4j with PowerMock at his [blog](http://code.haleby.se/2017/02/03/a-case-for-powermock/)\n\n[Older News](https://github.com/powermock/powermock/wiki/OldNews)\n\n## Documentation\n* [Getting Started](https://github.com/powermock/powermock/wiki/Getting-Started)\n* [Downloads](https://github.com/powermock/powermock/wiki/Downloads)\n* [Motivation](https://github.com/powermock/powermock/wiki/Motivation)\n* Javadoc\n  * [EasyMock API extension](http://www.javadoc.io/doc/org.powermock/powermock-api-easymock/1.7.0) ([PowerMock class](http://static.javadoc.io/org.powermock/powermock-api-easymock/1.7.0/org/powermock/api/easymock/PowerMock.html))\n  * [Mockito API extension](http://www.javadoc.io/doc/org.powermock/powermock-api-mockito/1.7.0) ([PowerMockito class](http://static.javadoc.io/org.powermock/powermock-api-mockito/1.7.0/org/powermock/api/mockito/PowerMockito.html))\n  * [Mockito2 API extension](http://www.javadoc.io/doc/org.powermock/powermock-api-mockito2/1.7.0) ([PowerMockito class](http://static.javadoc.io/org.powermock/powermock-api-mockito2/1.7.0/org/powermock/api/mockito/PowerMockito.html))\n  * [PowerMock Reflect](http://www.javadoc.io/doc/org.powermock/powermock-reflect/1.7.0) ([Whitebox class](http://static.javadoc.io/org.powermock/powermock-reflect/1.7.0/org/powermock/reflect/Whitebox.html))\n* Common\n  * [PowerMock Configuration](https://github.com/powermock/powermock/wiki/PowerMock-Configuration)\n  * [Bypass Encapsulation](https://github.com/powermock/powermock/wiki/Bypass-Encapsulation)\n  * [Suppress Unwanted Behavior](https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior)\n  * [Test Listeners](https://github.com/powermock/powermock/wiki/Test-Listeners)\n  * [Mock Policies](https://github.com/powermock/powermock/wiki/Mock-Policies)\n  * [Mock system classes](https://github.com/powermock/powermock/wiki/Mock-System)\n* [EasyMock](https://github.com/powermock/powermock/wiki/EasyMock)\n* [Mockito](https://github.com/powermock/powermock/wiki/Mockito)\n* [TestNG](https://github.com/powermock/powermock/wiki/TestNG)  \n* [Delegate to another JUnit Runner](https://github.com/powermock/powermock/wiki/JUnit_Delegating_Runner)\n* [Bootstrap using a JUnit Rule](https://github.com/powermock/powermock/wiki/PowerMockRule)\n* [Bootstrap using a Java Agent](https://github.com/powermock/powermock/wiki/PowerMockAgent)\n* [OSGi](https://github.com/powermock/powermock/wiki/osgi)\n* [Release Notes](https://github.com/powermock/powermock/wiki/ReleaseNotes)\n* [FAQ](https://github.com/powermock/powermock/wiki/FAQ) \n\n## Contributing to PowerMock\n\nPlease, read [the guideline](CONTRIBUTING.md) for a new contributor before start. \n\n### Support and discussion\nJoin the mailing-list [here](http://groups.google.com/group/powermock) for questions, feedback and support.\n\n"
  },
  {
    "path": "build.gradle",
    "content": "buildscript {\n    repositories {\n        mavenCentral()\n        jcenter()\n        maven {\n            url 'https://repo.spring.io/plugins-release'\n        }\n        maven {\n            url 'https://plugins.gradle.org/m2/'\n        }\n    }\n    dependencies {\n        classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7'\n        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'\n        classpath 'net.researchgate:gradle-release:2.4.0'\n        classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4'\n        classpath 'org.shipkit:shipkit:2.3.4'\n        classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.4.1'\n    }\n}\n\next{\n    gradleScriptDir = \"${rootProject.projectDir}/gradle\"\n\n    byteBuddy = \"1.12.7\"\n    easymockVersion = \"4.0.1\"\n    hamcrestVersion = \"1.3\"\n    assertjVersion = \"2.6.0\"\n    cglibVersion = \"3.2.9\"\n    objenesisVersion = \"3.2\"\n    javassistVersion = \"3.27.0-GA\"\n    junitVersion = \"4.12\"\n    junitRulesVersion = \"4.8.2\"\n    testngVersion = \"6.9.10\"\n    xstreamVersion = \"1.4.10\"\n    mockitoVersion = \"4.3.1\"\n    servletVersion = \"2.5\"\n    jacocoVersion = \"0.7.7.201606060606\"\n    eclipseJdt = \"3.3.0-v_771\"\n    checkstyleVersion= \"7.6.1\"\n    systemRulesVersion=\"1.18.0\"\n}\n\napply plugin: 'org.shipkit.java'\n\ndescription = 'PowerMock allows you to unit test code normally regarded as untestable.\\n' +\n        '        For instance it is possible to mock static methods, remove static initializers, allow mocking without dependency\\n' +\n        '        injection and more.\\n' +\n        '        PowerMock works by bytecode manipulation.\\n' +\n        '        PowerMock also contain some utilities that gives you easier access to an objects internal state.\\n' +\n        '        PowerMock can be used to test otherwise untestable code and also to achieve a cleaner separation between test\\n' +\n        '        and production code.'\n\napply from: \"${gradleScriptDir}/version.gradle\"\n\nallprojects{\n    apply plugin: 'propdeps-idea'\n}\n\napply from: \"${gradleScriptDir}/modules.gradle\"\n\njar{\n    enabled = false\n}\n\ntask wrapper(type: Wrapper) {\n    gradleVersion = '4.10.2'\n}\n"
  },
  {
    "path": "config/checkstyle/checkstyle.xml",
    "content": "<?xml version=\"1.0\"?>\n<!DOCTYPE module PUBLIC \"-//Puppy Crawl//DTD Check Configuration 1.3//EN\" \"http://www.puppycrawl.com/dtds/configuration_1_3.dtd\">\n<module name=\"Checker\">\n  <module name=\"UniqueProperties\"/>\n  <module name=\"Translation\"/>\n  <module name=\"TreeWalker\">\n    <module name=\"MissingOverride\"/>\n    <module name=\"StringLiteralEquality\"/>\n    <module name=\"ParenPad\">\n      <property name=\"tokens\" value=\"LITERAL_WHILE, ENUM_CONSTANT_DEF, EXPR, LITERAL_DO, QUESTION, LITERAL_CATCH, ANNOTATION_FIELD_DEF, LITERAL_FOR, CTOR_CALL, LITERAL_SWITCH, RESOURCE_SPECIFICATION, LITERAL_SYNCHRONIZED, LAMBDA\"/>\n    </module>\n    <module name=\"UnnecessaryParentheses\">\n      <property name=\"tokens\" value=\"STAR_ASSIGN, MINUS_ASSIGN, LITERAL_FALSE, BAND_ASSIGN, NUM_LONG, DIV_ASSIGN, NUM_DOUBLE, ASSIGN, MOD_ASSIGN, STRING_LITERAL, SR_ASSIGN, SL_ASSIGN, LITERAL_NULL, LITERAL_TRUE, NUM_INT, NUM_FLOAT, PLUS_ASSIGN, BXOR_ASSIGN, BSR_ASSIGN\"/>\n    </module>\n    <module name=\"OuterTypeFilename\"/>\n    <module name=\"NoLineWrap\"/>\n    <module name=\"HiddenField\">\n      <property name=\"ignoreConstructorParameter\" value=\"true\"/>\n      <property name=\"ignoreSetter\" value=\"true\"/>\n      <property name=\"tokens\" value=\"LAMBDA\"/>\n    </module>\n    <module name=\"MutableException\"/>\n    <module name=\"RightCurly\">\n      <property name=\"tokens\" value=\"LITERAL_ELSE, LITERAL_FINALLY\"/>\n    </module>\n    <module name=\"OuterTypeNumber\">\n      <property name=\"max\" value=\"4\"/>\n    </module>\n    <module name=\"NoFinalizer\"/>\n    <module name=\"EmptyLineSeparator\">\n      <property name=\"allowNoEmptyLineBetweenFields\" value=\"true\"/>\n      <property name=\"tokens\" value=\"INSTANCE_INIT, ENUM_DEF, STATIC_INIT\"/>\n    </module>\n    <module name=\"InterfaceTypeParameterName\"/>\n    <module name=\"CovariantEquals\"/>\n    <module name=\"NestedForDepth\"/>\n    <module name=\"RedundantModifier\">\n      <property name=\"tokens\" value=\"INTERFACE_DEF, ANNOTATION_FIELD_DEF, ENUM_DEF, RESOURCE\"/>\n    </module>\n    <module name=\"AbstractClassName\">\n      <property name=\"ignoreModifier\" value=\"true\"/>\n      <property name=\"ignoreName\" value=\"true\"/>\n    </module>\n    <module name=\"ConstantName\">\n      <property name=\"applyToPackage\" value=\"false\"/>\n      <property name=\"applyToPrivate\" value=\"false\"/>\n    </module>\n    <module name=\"ThrowsCount\"/>\n    <module name=\"AnnotationLocation\">\n      <property name=\"allowSamelineMultipleAnnotations\" value=\"true\"/>\n      <property name=\"tokens\" value=\"IMPLEMENTS_CLAUSE, INTERFACE_DEF, TYPECAST, PARAMETER_DEF, CTOR_DEF, VARIABLE_DEF, LITERAL_NEW, ANNOTATION_FIELD_DEF, LITERAL_THROWS, ENUM_DEF, ANNOTATION_DEF, CLASS_DEF, DOT, TYPE_ARGUMENT\"/>\n    </module>\n    <module name=\"AnonInnerLength\">\n      <property name=\"max\" value=\"60\"/>\n    </module>\n    <module name=\"NoWhitespaceAfter\">\n      <property name=\"tokens\" value=\"LNOT, INC, DOT, UNARY_MINUS, ARRAY_DECLARATOR, INDEX_OP, DEC, UNARY_PLUS, BNOT\"/>\n    </module>\n    <module name=\"NoWhitespaceBefore\">\n      <property name=\"tokens\" value=\"POST_DEC, GENERIC_END, COMMA, POST_INC\"/>\n    </module>\n    <module name=\"StaticVariableName\">\n      <property name=\"applyToPublic\" value=\"false\"/>\n      <property name=\"applyToPrivate\" value=\"false\"/>\n    </module>\n    <module name=\"NeedBraces\">\n      <property name=\"allowSingleLineStatement\" value=\"true\"/>\n      <property name=\"tokens\" value=\"LITERAL_DO, LITERAL_WHILE, LAMBDA\"/>\n    </module>\n    <module name=\"AvoidEscapedUnicodeCharacters\">\n      <property name=\"allowIfAllCharactersEscaped\" value=\"true\"/>\n    </module>\n    <module name=\"IllegalInstantiation\"/>\n    <module name=\"PackageName\"/>\n    <module name=\"LocalFinalVariableName\">\n      <property name=\"tokens\" value=\"PARAMETER_DEF\"/>\n    </module>\n    <module name=\"AvoidStarImport\">\n      <property name=\"allowClassImports\" value=\"true\"/>\n      <property name=\"allowStaticMemberImports\" value=\"true\"/>\n    </module>\n    <module name=\"ReturnCount\">\n      <property name=\"max\" value=\"5\"/>\n      <property name=\"maxForVoid\" value=\"3\"/>\n      <property name=\"tokens\" value=\"CTOR_DEF, LAMBDA\"/>\n    </module>\n    <module name=\"ClassTypeParameterName\"/>\n    <module name=\"TypecastParenPad\"/>\n    <module name=\"EmptyForInitializerPad\"/>\n    <module name=\"SeparatorWrap\">\n      <property name=\"tokens\" value=\"SEMI, RBRACK, COMMA, ARRAY_DECLARATOR, ELLIPSIS\"/>\n    </module>\n    <module name=\"RequireThis\"/>\n    <module name=\"SuperFinalize\"/>\n    <module name=\"IllegalType\">\n      <property name=\"tokens\" value=\"METHOD_DEF, PARAMETER_DEF\"/>\n    </module>\n    <module name=\"IllegalToken\">\n      <property name=\"tokens\" value=\"EOF, STAR_ASSIGN, DIV_ASSIGN, RESOURCES, MOD_ASSIGN, BSR_ASSIGN, TYPE_EXTENSION_AND, RESOURCE_SPECIFICATION, UNARY_PLUS, METHOD_REF, SL_ASSIGN, STRICTFP, RESOURCE, DOUBLE_COLON\"/>\n    </module>\n    <module name=\"ParameterNumber\">\n      <property name=\"max\" value=\"8\"/>\n    </module>\n    <module name=\"AbbreviationAsWordInName\">\n      <property name=\"allowedAbbreviationLength\" value=\"8\"/>\n    </module>\n    <module name=\"PackageDeclaration\">\n      <property name=\"matchDirectoryStructure\" value=\"false\"/>\n    </module>\n    <module name=\"DescendantToken\"/>\n    <module name=\"BooleanExpressionComplexity\">\n      <property name=\"max\" value=\"7\"/>\n    </module>\n    <module name=\"SuppressWarnings\"/>\n    <module name=\"MethodParamPad\">\n      <property name=\"tokens\" value=\"METHOD_CALL, ENUM_CONSTANT_DEF, CTOR_DEF, LITERAL_NEW, SUPER_CTOR_CALL\"/>\n    </module>\n    <module name=\"SuppressWarningsHolder\"/>\n    <module name=\"RedundantImport\"/>\n    <module name=\"MethodLength\">\n      <property name=\"countEmpty\" value=\"false\"/>\n      <property name=\"tokens\" value=\"CTOR_DEF\"/>\n    </module>\n    <module name=\"EmptyBlock\">\n      <property name=\"option\" value=\"text\"/>\n      <property name=\"tokens\" value=\"LITERAL_DEFAULT, LITERAL_ELSE, LITERAL_CASE, LITERAL_DO, INSTANCE_INIT, LITERAL_FOR, ARRAY_INIT, LITERAL_IF, LITERAL_TRY, LITERAL_SWITCH, STATIC_INIT, LITERAL_FINALLY, LITERAL_SYNCHRONIZED\"/>\n    </module>\n    <module name=\"MethodTypeParameterName\"/>\n    <module name=\"IllegalTokenText\"/>\n    <module name=\"PackageAnnotation\"/>\n    <module name=\"UpperEll\"/>\n    <module name=\"MemberName\">\n      <property name=\"applyToPrivate\" value=\"false\"/>\n    </module>\n    <module name=\"NestedTryDepth\">\n      <property name=\"max\" value=\"2\"/>\n    </module>\n    <module name=\"DefaultComesLast\"/>\n    <module name=\"TypeName\">\n      <property name=\"applyToPublic\" value=\"false\"/>\n    </module>\n    <module name=\"ImportOrder\">\n      <property name=\"ordered\" value=\"false\"/>\n    </module>\n    <module name=\"SuperClone\"/>\n    <module name=\"MethodName\">\n      <property name=\"applyToPublic\" value=\"false\"/>\n      <property name=\"applyToPackage\" value=\"false\"/>\n      <property name=\"applyToPrivate\" value=\"false\"/>\n    </module>\n    <module name=\"ParameterName\">\n      <property name=\"accessModifiers\" value=\"protected, public, private\"/>\n    </module>\n    <module name=\"ExecutableStatementCount\">\n      <property name=\"max\" value=\"50\"/>\n      <property name=\"tokens\" value=\"STATIC_INIT, CTOR_DEF, INSTANCE_INIT\"/>\n    </module>\n    <module name=\"NoClone\"/>\n    <module name=\"OperatorWrap\">\n      <property name=\"tokens\" value=\"STAR, BOR_ASSIGN, STAR_ASSIGN, MINUS_ASSIGN, BOR, EQUAL, BAND_ASSIGN, DIV_ASSIGN, DIV, MINUS, LAND, BXOR, QUESTION, LE, BSR, LT, COLON, GT, SL, BAND, GE, NOT_EQUAL, LITERAL_INSTANCEOF, MOD_ASSIGN, SR_ASSIGN, SR, TYPE_EXTENSION_AND, METHOD_REF, SL_ASSIGN, PLUS_ASSIGN, BXOR_ASSIGN, BSR_ASSIGN, MOD\"/>\n    </module>\n  </module>\n</module>\n"
  },
  {
    "path": "docs/changelog.txt",
    "content": "Change log 2.0.0\n* PowerMockito changes:\n** `verifyStatic` is replaced by `verifyStatic(Class)`\n** `mockStatic` does not reset mocking process anymore. As result you may get the `UnfinishedVerificationException` or `UnfinishedStubbingException`\n** Possible incapability due toString methods returns by default name of mocked.\n\nChange log 1.7.1\n* Fixed #832 Provide a new API for verifying static mock and deprecate old for Mockito\n\nChange log 1.7.0\n-----------------------------\n* Added supporting Mockito 2.8.9 for PowerMock 2.x (thanks to Gregor Stamac @gstamac for pull request)\n* Added supporting global ignore via configuration (issue # #801)\n* Added supporting org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker via PowerMock configuration (issues #793, #774)\n* Optimizations in powermock-reflect (thanks to Roman Leventov @leventov for pull request) (#724)\n* Migrated from Maven to Gradle (#728)\n* Implement #793 PowerMockMaker for Mockito 2: A new version of PowerMockMaker implemented. It does not conflict with Mockito MockMaker any more. Fix for #701 partially does not work any more, because ByteBuddy implementation of MockMaker always intercept calls to equals and return `true` only in case if passed object is the same instance of mocked object.\n* Fixed issue #722 IllegalArgumentException is output to standard error (thanks to Kotaro Nanri @k-nanri for pull request)\n* Fixed issue #717 Regression: MethodNotFoundException\n* Fixed issue #731 No methods matching the name(s) get were found in the class hierarchy for interfaces\n* Fixed issue #753 fix to upgrade code to be compatible with later versions of Mockito (thanks to emmaLP @emmaLP for pull request)\n* Fixed issue #763 whenNew not matching constructor when null is passed as first or last argument. (thanks to @podarsmarty podarsmarty for pull request)\n* Fixed issue #781 Call mocked equals static method instead of real (thanks to @Ilya-Gh Ilya Ghirici for pull request)\n* Fixed issue #772: PowerMockIgnorePackagesExtractorImpl should visit interfaces. (thanks to François Jacques @hypnoce for pull request)\n* Fixed issue with javax.xml and org.w3c. Previously when PowerMock was used with class which works with XML adding ``@PowerMockIgnore({\"org.w3c.*\", \"javax.xml.*\"})` was required. See examples: https://github.com/powermock/powermock-examples-maven/blob/master/spring-mockito-xml/src/test/java/org/powermock/examples/spring/mockito/SpringExampleTest.java\n\nChange log 1.6.6 (2016-11-04)\n-----------------------------\n* Added support for setting private static final fields in Whitebox.setInternalState  (thanks to Andrei Petcu @andreicristianpetcu for pull request)\n* Added support for specifying constructor parameters for Mockito for whenNew case (Only mock specific calls to new #31)\n* Fixed #668 @Mock fields are not injected anymore (1.6.5 regression)\n* Fixed #676 Using Powermock with Roo/AspectJ gives NullPointerException (thanks to Sebastian Saip @ssaip for pull request)\n* Fixed #656 TooManyActualInvocations when class is prepared for test.\n* Fixed #695 ClassNotFoundException when loading cglib enhanced classes created by Spring\n* Fixed Java 6 compatibility issue in org.powermock.utils.StringJoiner (which accidentally referenced Java 7 API's)\n* Fixed #701 StackOverflowError mocking final class extending non-public abstract class overriding equals method\n* Fixed #707 PowerMock should ignore and keep synthetic method/fields when modifies class\n* Fixed #645 jacoco offline instrumentation incompatibility with powermock byte-code manipulation when using @SuppressStaticInitializationFor \n* Fixed #704 PowerMockito 1.6.5 throws java.lang.SecurityException signer information mismatch \n* Refactoring: Move ProxyFramework from api modules to `reflect` module.\n* Renamed org.powermock.reflect.internal.WhiteboxImpl.getAllMetodsExcept to org.powermock.reflect.internal.WhiteboxImpl.getAllMethodsExcept (typo)\n* Refactoring: Fix performance issues, fix error handling issues, remove unused imports, remove verbose or redundant code constructs. (thanks to Mykhailo Kovalskyi @kovalsky for pull request)\n* Upgraded Assertj dependency from 3.4.1 to version 3.5.2\n* Upgraded Javaassist dependency from 3.20.0-GA to version 3.21.0-GA\n* Upgraded Objenesis dependency from 2.2 to version 3.4\n\nChange log 1.6.5 (2016-04-30)\n-----------------------------\n* Add ability to chain returns with doReturn() (thanks to \"gauee\" for pull request) (issue #599)\n* Code quality improvement, @Override annotation should be used on any method overriding (since Java 5) or implementing (since Java 6) another one\n* PowerMockRunner now processes JUnit Rules correctly (thanks to Stefan Birkner for pull request) (issue 427)\n* Added support for @TestSubject in EasyMock API. This is the equivalent of @InjectMocks in Mockito (big thanks to Arthur Zagretdinov for pull request)\n* Added experimental support for mockito 2.x\n* Ensuring JVM method size limit is never exceeded. Throw an user frendly exception if method size is exceeded. (thanks to Tomasz Przybyla for pull request) (issue #661)\n* Fix #214: Whitebox.invokeConstructor may not work as expected with overloaded constructors\n* Fix #352: PowerMockRunner should run tests defined in super class\n* Fix #510: Static method mocking with Mockito 1.9.5 and Powermock fails with Java 8 Consumer Interface\n* Fix #512: @PrepareForTest on method not working with PowerMockRule\n* Fix #652: PowerMock stubbing void method don't work for overloaded methods\n* Fix #648: TestNG SkipException doesn't work with PowerMock\n* Fix #634/#632: Add workaround as fix  for Mockito 1+. Wait fix from Mockito team for Mockito 2.\n* Fix #590: suppress(method) doesn't work on a @Spy/PowerMockito.spy\n* Upgraded commons-logging dependency to version 1.2\n* Upgraded objenesis dependency to version 2.2\n* Upgraded TestNG dependency to version 6.9.10.\n* Upgraded xStream dependency to version 1.4.9.\n* ASM for PowerMock Javaagent repackaged from new version 5.0.4\n\nChange log 1.6.4 (2015-12-11)\n-----------------------------\n* DelegatingPowerMockRunner now implements Filterable interface to allow running for example individual test methods (thanks to chang-chao for pull request)\n* Fixed jacoco/powermock integration issue (thanks to Evgeny Astafyev for pull request)\n* Improvements to StackTraceCleanerProvider which cleans powermock classes from a stack trace\n* Replaced usage of uberjar mockito-all with mockito-core (thanks to Petr Široký and René Scheibe for helping out)\n* Code quality improvement, constructors only call non-overridable methods (thanks to Christian Ivan for pull request)\n\nChange log 1.6.3 (2015-10-02)\n----------------------------\n* Mock name in @Mock(name=\"abc\") annotations are no longer ignored for the Mockito API extension\n* Fixed NPE in withArguments() constructor (thanks to Tomoyuki Saito for pull request)\n* Upgraded Javassist dependency to version 3.20.0-GA.\n* Using soft reference in classloader cache\n* MockClassloader now extends Javassist Loader classloader to implement findClass etc\n* PowerMock now works better with ByteBuddy (issue 579)\n* This allows creating mocks in the applyInterceptionPolicy method of MockPolicy, which in turn allows using MockPolicy together with PowerMockRule (issue 581).\n* Upgraded the powermock-easymock extension to use EasyMock 3.4\n\nChange log 1.6.2 (2015-01-03)\n----------------------------\n* PowerMockRunnerDelegate annotation now uses @Inherited (thanks to Henrik Kaipe for pull request)\n* Tests can now have multiple constructors (thanks to Henrik Kaipe for pull request)\n* Cleanup pom files and added version numbers (thanks to René Scheibe for pull request)\n* Fix \"Test class can only have one constructor\" issue that occurs when a JUnit or 3rd-party delegate runner (specified by a PowerMockRunnerDelegate annotation) can only deal with one public constructor. (thanks to Henrik Kaipe for pull request)\n* Packaged some of the Mocktio classes internally since Mockito is moving from CgLib to ByteBuddy. (thanks to Brice Dutheil for the pull request).\n* Upgraded Javassist dependency to version 3.19.0-GA.\n* Upgraded TestNG dependency to version 6.8.21.\n* The PowerMock EasyMock Api now depends on EasyMock 3.3.1.\n\nChange log 1.6.1 (2015-01-03)\n----------------------------\n* The PowerMock EasyMock Api now depends on EasyMock 3.3. Note that 1.6.0 also works with this version of EasyMock _if_ cglib-nodep 2.2.2 is used as EasyMock transitive dependency.\n* PowerMock JUnit Module now supports JUnit 4.12 (Thanks to Henri Tremblay for the pull request).\n* Upgraded TestNG from 6.8.8 to 6.8.13.\n* Fixed Mockito 1.10.9+ incompatibility, by repackaging CGLIB MockMaker (issue 524). Thanks to Brice Dutheil for the pull request.\n\nChange log 1.6.0 (2014-11-27)\n-----------------------------\n* It's now possible to verify private final overloaded methods in the Mockito Extension API. For example:\n    verifyPrivate(tested).invoke(method(MyClass.class, \"myOverloadedMethodName\", String.class, String.class)).withArguments(anyString(), captor.capture());\n* Upgraded Mockito API extension to work with version Mockito 1.10.8.\n* PowerMock now builds for Java 6 and not Java 5.\n* You can now use other runners in combination with the PowerMockRunner without using a JUnit Rule. This leaves the actual test-execution to or another runner of your choice.\n  For example tests can delegate to \"SpringJUnit4ClassRunner\", \"Parameterized\" or the \"Enclosed\" runner. This also allows PowerMock to (without any modifications) support future new JUnit-features from day one! Usage example:\n\n  @RunWith(PowerMockRunner.class)\n  @PowerMockRunnerDelegate(Parameterized.class) // Use the parameterized JUnit in combination with the PowerMockRunner\n  @PrepareForTest(SuppressConstructorDemo.class)\n  public class SuppressConstructorDemoTest {\n    ...\n  }\n  (Big thanks to Henrik Kaipe for this excellent pull request).\n\nChange log 1.5.6 (2014-09-04)\n-----------------------------\n* Changed so that the MockClassLoader throws ClassNotFoundException instead of Javassist's NotFoundException when a class isn't found (thanks to Mikael Petterson for the pull request).\n* Final equals methods should now work with Mockito and not cause stackoverflow (thanks to Peer Hartmann for pull request)\n* Removed redundant cast when creating a class replicas for final system classes.\n* Cleaned up some code in the ClassReplicaCreator class\n* Added support for answers, name and extract interfaces in PowerMockito when using annotations (@Mock). Note that answers doesn't work for final classes or methods! (issue 486).\n* PowerMockIgnore is now taken into account when using the Java Agent PowerMockRule.\n* Improved java agent automatic bootstrap mechanism to work better for newer JDK's.\n* PowerMock now finds default methods in Java 8 (issue 513).\n* Annotations such as @Mock and @InjectMocks can now be used with the JUnit Java Agent.\n* Proxy framework is loaded from the the JUnit Java Agent which means that all Whitebox methods work as expected.\n\nChange log 1.5.5 (2014-05-28)\n-----------------------------\n* Updated OSGi metadata\n* MockClassLoader.getResources no longer loads same file twice (thanks to Kelsey Rider for the patch)\n* Added getResourceAsStream and getResource to DeferSupportingClassLoader which defers loading to the deferring classloader.\n* Added ability to adjust the classpath when running the a test using the @UseClassPathAdjuster annotation. This is useful when integrating PowerMock with certain third-party JUnit runners (thanks to Jonas Berlin for the patch).\n* Upgraded to Javassist 3.18.2-GA.\n* Moved project to github (issue 493).\n* Upgraded to TestNG 6.8.8.\n* Removed accidental JUnit dependency to Objenesis and XStream classloading projects.\n\nChange log 1.5.4 (2014-01-29)\n-----------------------------\n* Removed OSGi metadata because they didn't work properly\n* Fixed an issue when setting up private method expectations with multiple arguments in Mockito.\n* Added support for suppressing static initializers using TestNG (issue 256) (thanks to majorpetya for the patch).\n* PowerMock Java agent works in Java 8 (issue 475) (thanks to iirekm for help).\n* Moved bundled asm packages into the powermock package for the PowerMock Java Agent module to avoid classloading issues.\n\nChange log 1.5.3 (2014-01-10)\n-----------------------------\n* Added OSGi metadata to manifest files (issue 204) (thanks to Gabor Liptak for patch)\n* Upgraded to Javassist 3.18.1-GA.\n* Test case with expectedExceptions no longer fails when using PowerMock with TestNG (issue 366) (thanks to majorpetya for the patch).\n* Fixed a classloading issue with the JUnit4TestSuiteChunkerImpl (thanks to Robert Gay for the patch)\n* Updated objenesis to version 2.1\n\nChange log 1.5.2 (2013-11-18)\n-----------------------------\n* Fixed PowerMock OOM (OutOfMemory) issues with Mockito (big thanks to Henrik Karlsson for the patch).\n* PowerMock EasyMock extension API now supports EasyMock version 3.2.\n* Added jacoco agent to be deferred by the PowerMock classloader\n* Updated TestNG dependency to 6.8.7.\n\nChange log 1.5.1 (2013-06-19)\n-----------------------------\n* Maven no longer adds classpath to jar manifests when building PowerMock (issue 413).\n* PowerMockRunner now supports both MethodRules and TestRules to comply with JUnit 4.11 (thanks to \"Boris Code\" for the patch) (issue 419).\n* Slf4j MockPolicy in Mockito now works again (issue 431).\n* Removed synchronized from all MockGateway methods in order to make it work with multi-threaded Mockito.\n* The PowerMock runner for JUnit now supports assumeTrue(..) statements (issue 408).\n* Mocked system classes are now invoked when it's casted into another (non-final) type (thanks to Jonatan Jonsson for the patch) (issue 445).\n* TestNG state is cleaned up in a better way when a test fails (thanks to Jonatan Jonsson for the patch).\n* PowerMock byte-code manipulation transformers now ignores classes it cannot load. This means that PowerMock works with better SPI's that have compile-time dependencies that are not available at runtime.\n* Upgraded Javassist to version 1.8.0-GA.\n* Upgraded to TestNG module to version 6.8.5\n* Upgraded to JUnit module to version 4.11\n\nChange log 1.5 (2012-12-04)\n---------------------------\n* Added var-args to mockStatic in the PowerMockito API. You can now do: \n  mockStatic(A.class, B.class, C.class);\n* Suppression is now working for overridden methods (issue  364, 51). Thanks to  hpbeem for the patch.\n* PowerMock junit module now supports JUnit rules for version 4.9+ (issue 344). Thanks to Andreas Kutschera for the patch.\n* Fixed is with PowerMock JUnit runner that failed to parse JUnit versions including characters such as 4.9b2. (issue 381).\n* Mockito extension API now uses Mockito 1.9.5 (issue 398) \n* Updated TestNG dependency to version 6.8\n* Added support for easily mocking all constructors of a class in the Mockito extension API. For example: whenNew(X.class).withAnyArguments().thenReturn(xMock); (issue 405).\n* Upgraded to Javassist 3.17.1-GA, this means that PowerMock works in Java 7!\n\nChange log 1.4.12 (2012-04-05)\n------------------------------\n* Really added missing class, PowerMockTestCase, to testng full release jar (issue 327). \n* PowerMock JUnit module now works with JUnit 4.10 (thanks to Diego Coronel for the patch) (issue 367)\n* Changed name from org.powermock.api.mockito.mockpolicies.Slf4jMockPolicy to org.powermock.api.mockito.mockpolicies.Slf4jMockPolicy in the Mockito extension API.\n* Upgraded Javassist to version 3.16.1.GA.\n* DeferSupportingClassLoader now overrides ClassLoader.findResources() which enables classes loaded by MockClassLoader to be to find resources via ClassLoader.findResources(...). Thanks to wrussellmorris for the patch (issue 380).\n* Updated TestNG dependency to version 6.4\n\nChange log 1.4.11 (2012-01-05)\n------------------------------\n* Fixed an OutOfMemory issue in PowerMockRunner (issue 346).\n* Added Sfl4jMockPolicy to the Mockito extension API, thanks to Alexandre Normand for the patch.\n* Replaced ${version} to ${project.version} in all pom files (thanks to pvdissel for the patch) (issue 287).\n* Added work-around to stub some final system classes (such as java.util.UUID) (issue 354).\n* Improved the PowerMock Java agent support. It should now work together with multiple java agents (thanks to Magnus Jungsbluth for the patch) (issue 357).\n* Upgraded TestNG module to 6.3.1.\n* Upgraded EasyMock extension API to use version 3.1 of EasyMock. This version should fix a couple of OutOfMemory issues.\n* PowerMockito is updated to use Mockito 1.9.0\n* setUp-method with @Before annotation is no longer executed twice when extending TestCase (issue 356)\n* Upgraded classloader xstream deepcloner to XStream 1.4.2 (issue 345)\n\nChange log 1.4.10 (2011-08-23)\n------------------------------\n* Added missing class, PowerMockTestCase, to testng full release jar (issue 327).\n* Fixed test initialization error when using PowerMock Mockito API in Ant (issue 333).\n* Upgraded to Javassist 3.15 GA (issue 338).\n* Upgraded TestNG module to TestNG 6.2.\n* Mockito @InjectMocks annotations on superclasses of test class are no longer ignored (issue 343).\n* MockClassloader now defers the loading of classes in \"org.pitest.*\" to the system classloader. This means that you should be able to use PIT (http://pitest.org) without adding @PowerMockIgnore(\"org.pitest.*\") to each test class (issue 337).\n* PowerMockito now works with Mockito 1.9-rc1 but will not include the new artifact by default because it's still rc (issue 339).\n* Removed PowerMockRule from full jar in release process (issue 325).\n\nChange log 1.4.9 (2011-05-02)\n-----------------------------\n* Fixed an issue when mocking system classes containing fields of type Class, Classloader or synthetic fields such as java.util.ServiceLoader.\n* TestNG PowerMockObjectFactory now sets the thread context classloader to the PowerMock mock classloader (issue 315).\n* TestNG PowerMockObjectFactory now only uses PowerMock classloader and byte-code manipulation if the test class or a method declared in this method is annotated with @PrepareForTest or @SuppressStaticInitializerFor. This introduces a non-backward compatible change so if you're currently using mock injection (e.g. annotating a field with @Mock) you must now also use @PrepareForTest or @SuppressStaticInitializerFor for the mocks to be injected (issue 299).\n* Upgraded TestNG module to TestNG 6.0.1 (issue 316).\n* Fixed an issue with the PowerMock JUnit runner that prevented a JUnit Rule to throw an exception failing the test (issue 311).\n* Fixed an issue with test state clearing while running a PowerMock enabled test as an Eclipse PDE test (issue 309).\n* Classloader based PowerMock JUnit Rules now supports suppressing static initializers\n* Improved state clean-up in TestNG module when extending from PowerMockTestCase.\n* Automatic creation and injection of mocks to a field annotated with @Mock does no longer work if you're not extending from PowerMockTestCase in the TestNG classloading module (side-effect of issue 299).\n* Removed the classloading version of PowerMockRule from the powermock-easymock-full and powermock-mockito-full release jars. You need to download the rule implementations manually since there are now two different implementations to choose from. (issue 318)\n* Implemented experimental support for bootstrapping PowerMock using a Java agent. With the agent you won't run into classloading issues that you may with the standard way of bootstrapping. The new project is called junit4-rule-agent for JUnit and testng-agent for TestNG.\n\nChange log 1.4.8 (2011-02-26)\n-----------------------------\n* Fixed a bug in Whitebox which prevented passing null parameters to methods.\n* PowerMock now supports mocking static final inner classes and member Enums (issue 95). \n* Fixed a bug in PowerMockito that sometimes caused the finalize method to be called instead of the expecting method when setting up expectations (issue 308).\n* Upgraded TestNG module to TestNG 5.14.6\n\nChange log 1.4.7 (2010-12-27)\n-----------------------------\n* The MemberModifier API now checks that the replacing method returns the same type and have the same number of parameters as the original method otherwise an IllegalArgumentException is thrown (issue 285).\n* Fixed a bug which made it impossible to mock private methods with multiple arguments (issue 289).\n* Removed some unwanted debug messages from the TestNG module.\n* Updated javadoc in Whitebox and WhiteboxImpl.\n* EasyMock and Mockito extension API now supports mocking new invocations with var args parameters when var args paramters is not the first parameter (issue 163).\n* Various improvements to var args handling for both methods and constructors.\n* Upgraded to Javassist 3.14 (issue 295).\n* Upgraded junit module to use JUnit 4.8.2 (issue 296).\n* You no longer need to prepare system classes that are not final and whose methods are not static, final or native in a special way (by prepare the class calling the system class method) (issue 300).\n* Added method \"defaultConstructorIn\" to the MemberMatcher API so that you can e.g. suppress a default constructor using suppress(defaultConstructorIn(SomeClass.class)) (issue 302).\n* PowerMock now cleans up EasyMock state after each test case which significantly decreases memory consumption.\n* PowerMock now cleans up most Mockito state after each test case which decreases memory consumption.\n* Major refactoring of the classloading module. It has been split up in a way that allows for different object deep-cloning mechanisms. The previous implementation is now called powermock-classloading-objenesis and there's also a new one called powermock-classload-xstream. The latter uses X-Stream for deep-cloning. This means that if you're using the PowerMock JUnit Rule you must also depend on one of the two deep-cloner implementations.\n\nChange log 1.4.6 (2010-10-13)\n-----------------------------\n* Changed project structure, all group id's are now \"org.powermock\" but most artifact id's are the same. There are two exceptions, org.powermock.tests and org.powermock.examples. Artifact module-test-powermock has been renamed to module-test-easymock and module-test-powermockito has been renamed to module-test-mockito (issue 234).\n* Removed all third-party repositories from the pom's to allow for Maven central syncing.\n* PowerMock can now be built with Maven 3 (issue 283).\n* Prepared pom's for Maven central synching.\n* Upgraded the TestNG module to version 5.14 (issue 275).\n* Fixed a bug in Whitebox which caused some overriden methods to be treated as overloaded (issue 276).\n\nChange log 1.4.5 (2010-08-30)\n-----------------------------\n* The EasyMock API extension should now work when testing Eclipse plugins and running the tests as PDE (JUnit Plugin) tests (issue 264)\n* Deprecated \"andReturn\" in the stubber API and added \"toReturn\" instead. The API now reads e.g. \"stub(method(\"methodName\")).toReturn(new Object());\"\n* Added the \"toThrow\" method to the stubber API. You can now do e.g. \"stub(method(\"methodName\")).toThrow(new Exception());\" (issue 182)\n* Whitebox#setInternalStateFromContext now support field matching strategies. By default all context fields that matches a field in the target class or instance is copied to the instance. If the strategy is changed from MATCHING to STRICT then an exception will be thrown if the context contains a field that cannot be copied to the target. Note that this change may cause backward incompatibility if you're currently using setInternalStateFromContext in your code. (issue 221)\n* Fixed an issue that was introduced in version 1.4 when support for partial mocking of instance methods in final system classes not having a default constructor was added. The bug caused an javassist.CannotCompileException exception when mocking certain classes such as java.lang.Console (issue 272).\n* Removed PowerMock specific classes to support mocking of signed classes in the EasyMock extension API since nowadays EasyMock supports this out of the box. This makes PowerMock less dependent on a specific EasyMock version and fixes and patches in EasyMock automatically applies to PowerMock in the future as well. (issue 273)\n* Upgraded the TestNG module to version 5.13.1.\n* Whitebox#newInstance(..) now supports instantiating interfaces and arrays. An exception is thrown when trying to instantiate an abstract type (issue 193).\n\nChange log 1.4 (2010-07-22)\n---------------------------\n* Implemeted support for mocking instance methods of final system classes with the Mockito extension API (issue 169)\n* Partial mocking of instance methods in final system classes not having a default constructor now works in the EasyMock extension API (issue 170)\n* The deep cloner can now clone java.reflect.Method objects correctly to a different classloader.\n* Fixed a critical bug in the ClassloaderExecutor which prevented it from running methods returning void. This affected the PowerMockRule which prevented it from executing test methods (even though it looked like it did) (issue 268, also closes issue 245)\n* Upgraded to Javassist 3.13 (issue 269)\n* Fixed some problems with Withbox regarding invocation of var args member class constructors and methods (issue 267).\n* Partial mocking of public static methods now works in Mockito (issue 261)\n* Better clean-up in test runner which fixes some java.lang.OutOfMemoryError errors in large test suites.\n\nChange log 1.3.9 (2010-07-14)\n----------------------------------\n* Upgraded the Mockito extension API to support Mockito 1.8.5\n* Upgraded the EasyMock extension API to support EasyMock 3.0 (issue 259)\n* Spying with PowerMockito now retains object state (issue 263)\n\nChange log 1.3.8 (2010-05-13)\n-----------------------------\n* Fixed a bug in DeepCloner which caused a NullPointerException for arrays containing null values.\n* Changed groupId of the PowerMock JUnit Rule project to org.powermock.modules.\n* Included PowerMock rule in the released artifacts\n* verifyNew with arguments no longer throws NullPointerException when missing expectation in the Mockito extension API.\n* EasyMock API extension now supports mock creation of classes whose hashCode implementation depends on constructor initialization.\n* It's now allowed to use verifyNew multiple times just as with verify in standard Mockito (issue 251)\n* Mockito extension API now supports mocking and stubbing equals and hashcode.\n* Fixed an issue in the core mock classloader that accidentally caused any previous deferred packages to be overwritten when adding new packages to be ignored.\n* Upgraded to Javassist 3.12 (issue 254)\n* Upgraded to TestNG 5.12 (issue 250)\n* Improved error messages in TestNG when running inside Eclipse\n\nChange log 1.3.7 (2010-03-22)\n-----------------------------\n* Added support for JUnit 4.8.1 (issue 226)\n* Added support for Mockito 1.8.4\n* Fixed so that a \"mock name\" is set in the Mockito extension API. Fixes NullPointerException when e.g. toString is invoked on a mock. (issue 239)\n* Changed method signature on \"mockStatic\" to return void in the Mockito extension API.\n* Fixed the \"Internal error: Run delegates were 0\" bug when using a test class hierarchy and the PowerMock JUnit runner when no tests are defined in a parent test class (issue 241).\n* Added support for deep cloning objects containing self references using the DeepCloner.\n* New experimental approach for bootstrapping PowerMock is supported using a JUnit rule called PowerMockRule (available in JUnit 4.7+). This allows you to use other JUnit runners than the PowerMock one (PowerMockRunner) while still benefiting from PowerMock's functionality.\n* Added support for suppressing all constructors in a class using suppress(constructorsDeclaredIn(X.class)).\n* Added support for suppressing all constructors and methods in a class suppress(everythingDeclaredIn(X.class)).\n\nChange log 1.3.6 (2010-03-10)\n-----------------------------\n* Added testng to full release project.\n* Fixed so that classloader executor supports runnable's.\n* DeepCloner now supports reference cloning.\n* DeepCloner now supports cloning enum constants.\n* DeepCloner now supports cloning standard java types (using simple serialization).\n* DeepCloner now supports cloning fields in a hierarchy.\n* DeepCloner now supports cloning class fields.\n* Fixed a bug in the Wildcard matcher which resulted in that classes located in packages containing \"junit.\", \"java.\", \"sun.\" in their name was never prepared for test (issue 225).\n* Fixed so that you can mock anonymous inner classes with the Mockito API extension (issue 227).\n* Nested classes declared inside the test case are automatically prepared for test.\n* Minor improvement in the byte-code manipulation; only package private classes are changed to public.\n* Upgraded he EasyMock extension API to use EasyMock class extension 2.5.2 (due to internal changes in EasyMock it's not backward compatible with older versions).\n* Upgraded to Objenesis for powermock-reflect to 1.2.\n* Fixed so that MockGateway now finds the correct method to invoke when several overloaded method candidates are found (issue 229).\n* Upgraded to Mockito 1.8.3.\n* Added support for Mockito annotations @Spy, @Captor and @InjectMocks.\n* Mockito extension now supports real partial mocking for private (and private final) methods (both static and instance methods) using PowerMockito.doReturn(..), PowerMockito.doThrow(..) etc.\n* Added support for MockSettings and Answers when creating class or instance mocks in Mockito extension, e.g. \"FinalClass mock = mock(FinalClass.class, Mockito.RETURNS_MOCKS);\".\n\nChange log 1.3.5 (2009-12-13)\n-----------------------------\n* Removed EasyMock maven dependencies from the JUnit legacy runner since they're not needed.\n* Fixed a bug in WhiteboxImpl#findUniqueConstructorOrThrowException which caused an additional constructor to be found when a class was prepared for test (issue 189).\n* Fixed the maven assembly so that it now produces two full jar files, one for Mockito and one for EasyMock. These contains the sources as well.\n* Mockito extension API now supports Mockito 1.8.1 & 1.8.2.\n* java.lang.Object#getClass is no longer mockable by default. The reason is that it may lead to an unexpected method invocation exception using EasyMock in some equal implementations. It's possible to override this behavior.\n* DeepCloner should now support cloning of static final fields on SUN JVM.\n* Fixed a minor bug in Whitebox#getInternalState so that a better error message is given when the instance argument is null (issue 205).\n* Fixed some typos in the javadoc of PowerMockito#verifyNew (issue 187).\n* Fixed so that Whitebox#getInternalState(..) now supports passing in super types as field-type critiera (issue 210).\n* Fixed so that Whitebox#getInternalState(..) and Whitebox#setInternalState(..) doesn't cause NPE when too many fields matched the criteria (issue 211).\n* Basic support for TestNG (5.11) implemented.\n* Fixed so that Whitebox#invokeMethod now works for overridden methods.\n* Implemented findResource in classloader, this means that you should be able to locate resources in classpath (issue 143).\n* JUnit runner and TestNG object factory now clears MockRepository state upon instantiation. This is useful in cases where a previous test has used e.g. PowerMock#createMock(..) to create a mock without using the runner/factory which means that there would be some state left in the MockRepository that hasn't been cleared.\n\nChange log 1.3.1 (released 2009-10-28)\n--------------------------------------\n* Critial bug resolved in the PowerMock JUnit 4.7 runner: Before tests would not be executed at all if a JUnit rule was used in the test (even though it looked like they were). This has now been resolved an thus support for JUnit 4.7 rules should _really_ work.\n* DeepCloner now supports cloning of one dimensional arrays, primitives, enums and collections.\n* Test case is now always prepared for test even if no @PrepareForTest annotation is specified\n* Fixed a bug in Whitebox#setInternalState so that it now works to supply an array when specifying a method name again.\n* Improved javadoc in Whitebox class\n* Upgraded EasyMock extension API to depend on EasyMock 2.5.2 (EasyMock class extensions are still version 2.4 since that's the latest release right now).\n\nChange log 1.3 (released 2009-10-06)\n------------------------------------\n* Classes that will have their static initializers suppressed are automatically added to prepare for test in mock policies.\n* Added a toString implementation for TestMethodResultImpl\n* Added a toString implementation for TestSuiteResultImpl\n* suppressMethod(Class...classes) now takes a class and additional classes as var args (i.e. suppressMethod(Class cls, Class...classes). This makes it easier to suppress all methods of a particular class for only one class.\n* Invoking reflection methods now works again. This failed in version 1.2 and 1.2.5 when PowerMock begun supporting mocking of system classes. E.g. MyClass.class.getClassloader() now works again even if MyClass is prepared for test.\n* The standard JUnit 4 runner has been verified to work with JUnit 4.6 and 4.7. The version dependency for JUnit4 is thus changed from [4.4,4.5] to [4.4,4.7].\n* Classes prepared for test in parent test classes are now automatically prepared for test as well. I.e. if Test Case A extends Test Case B and A prepares X.class and B prepares Y.class then both X and Y will be prepared for test. Before only X was prepared for test.\n* Fixed a bug in Whitebox which prevented it from instantiating classes with constructors combining normal and var-arg parameters. The same was fix was applied to method invocations as well.\n* Fixed so that WhiteboxImpl#findMethodOrThrowException(..) throws a TooManyMethodsFoundException if a potential method had previously been found and a new matching var-args method was found.\n* Fixed so that WhiteboxImpl#findConstructorOrThrowException(..) throws a TooManyConstructorsFoundException if a potential constructor had previously been found and a new matching var-args constructor was found.\n* Fixed a bug so that when Whitebox looks for a var args method it now also checks that the component type of the var args array is the same as the supplied argument type(s).\n* Implemented so that expectPrivate in the EasyMock extension API can be used without specifying a method name. The method is looked up by using the argument types.\n* Extended the Whitebox.setInternalState functionality to accept a var-args list of values to set on an object. I.e. you can now do Whitebox.setInternalState(object, myState1, .., myStateN).\n* Upgraded to Javassist 3.10 (3.11 doesn't work with PowerMock due to a bug or backward incompatibility in Javassist).\n* Fixed a bug in the EasyMock extension API regarding suppression of methods so that it now uses Whitebox.getMethods(..) instead of Whitebox.getMethod(..).\n* Mocking of static methods in final system classes now works with the Mockito extension (because of a bug fix in Javassist 3.10)\n* PowerMock now changes the context class-loader to the MockClassloader which means that you don't need to use @PowerMockIgnore as often as before. This solves many issues with frameworks that creates new instances using reflection like log4j, hibernate and many XML frameworks. This fix is not backward compatible with version 1.2.5! If you've been using PowerMockIgnore in your test you may need to remove it (or update the ignored package list) otherwise the test might fail.\n* Implemented support for setting internal state from a context (using Whitebox.setInternalStateFromContext(..)).\n* Error message differ between static or instance type fields when internal state cannot be set because a field wasn't found.\n* PowerMock now supports mocking instance methods of final system classes (such as java.lang.String). To do this you need to prepare the class that invokes the method of the system class. Note that partial mocking of instance methods in final system classes doesn't yet work if a constructor needs to be invoked on the mock.\n* You can now mock new instance calls to final system classes in the same was you'd mock any other new instance call.\n* Improved error message in Whitebox when getting a method or constructor which was not found and no parameter types were supplied.\n* The state of classes that should have their static intializers suppressed are no longer clear after each atomic test. This means that suppression of static initializers works (again) in test suites.\n* Begun working with support for TestNG (thanks to Dan Fabulich for helping us with this).\n* Deprecated Whitebox#getInternalState(Object object, String fieldName, Class<?> where, Class<T> type), use \"Whitebox.<Type> getInternalState(Object object, String fieldName, Class<?> where)\" instead.\n* Changed return type of Whitebox#getInternalState(Object object, String fieldName) from Object to T. This means that you can avoid cast using e.g. \"Whitebox.<MyType> getInternalState(instance, \"myFieldName\")\".\n* Changed return type of Whitebox#invokeMethod(..) from Object to T. This means that you can avoid cast using e.g. \"Whitebox.<MyType> invokeMethod(..)\".\n* JUnit test runner now supports JUnit 4.7 rules\n* Upgraded the Mockito extension to use Mockito 1.8\n* Created a reusable component (PowerMockIgnorePackagesExtractorImpl) that can be used by test runners to extract which packages that should be ignored in a test case.\n* Removed mockStatic(Class<?> type, Method method, Method... methods), mockStaticPartial, mockPartial, mock(Class<T> type, Method... methods) & mock(Class<T> type, Method... methods) from the Mockito extension API. You should use PowerMockito.spy instead.\n* When using the PowerMock Mock annotation with Mockito the method names (previously used for partial mocking) are ignored. They are no longer needed, just use PowerMockito.spy instead.\n* Mockito extension API support for private methods expectations using PowerMockito.when(..).\n* Fixed so that Whitebox error message prints correct parameter types when a MethodNotFoundException is thrown if a method with correct name but wrong parameter types were specified.\n* EasyMock extension API: You can now manually use replay(..) or verify(..) and then fall back on replayAll(..) verifyAll(..) even if a mock has previously been replayed/verified. I.e. replayAll/verifyAll only replays and verifies mocks that has previously not been manually replayed/verified.\n* WhiteboxImpl#getField(..) now check for null returned from Class.getSuperclass() to avoid NullPointerException when type is an interface (thanks to Ben Chatelain for the patch)\n* Deprecated org.powermock.core.classloader.annotations.Mock, you should now use the Mock annotation in respective extension API instead. For EasyMock this is org.powermock.api.easymock.annotation.Mock and for Mockito it's org.mockito.Mock.\n* Packages ignored for test in parent test classes are now automatically ignored as well when using @PowerMockIgnore. I.e. if Test Case A extends Test Case B and A ignores X and B ignores Y then both X and Y will be ignored in the test case. Before only X was ignored.\n* The method IExpectationSetters<Object> expectNew(String fullyQualifiedName, Object... arguments) in the EasyMock extension API changed return type to <T> IExpectationSetters<T> expectNew(String fullyQualifiedName, Object... arguments).\n* Improved error message for Whitebox#getConstructor when no constructor was found.\n* Fixed a bug in PowerMockito's CgLibProxyFramework#getUnproxiedType(..) so that it now _really_ returns the unproxied type.\n* You can now mock construction of new objects using the Mockito extension. To do so use PowerMockito#whenNew(..), e.g. whenNew(MyClass.class).withArguments(myObject1, myObject2).thenReturn(myMock). Verification can be done with PowerMockito#verifyNew(..), e.g. verifyNew(MyClass.class).withArguments(myObject1, myObject2).\n* Annotation support has been integrated in the test runners (both for JUnit and TestNG) so there's no need to specify the AnnotationEnabler listener using @PowerMockListener(AnnotationEnabler.class). It works both for the EasyMock and Mockito extension API's. This means that org.powermock.api.easymock.powermocklistener.AnnotationEnabler and org.powermock.api.mockito.powermocklistener.AnnotationEnabler has been deprecated.\n* Whitebox#getInternalState(..) and Whitebox#setInternalState(..) now uses isAssignableFrom instead of equals when looking for field types.\n* Added a new api-support project that contains functionality shared between all mock API projects\n* Mockito extension API now supports suppressing constructors, fields and methods.\n* ProxyFramework is now registered from the test runner instead of the extension API. This means that Whitebox always works correctly in the test cases regardless if the mock api is used or not.\n* Test classes are now always prepared for test automatically. This means that you can use suppressConstructor(..) and mock final system classes more easily since you don't have to prepare the actual test class for test. In some cases this change is not backward compatible with version 1.2.5. These cases are when you've tried to suppress a constructor but have forgot to prepare the test class for test as well.\n* @PowerMockIgnore now accept wildcards, this means that if you want to ignore all classes in the \"com.mypackage\" package you now have to specify @PowerMockIgnore(\"org.mypackage.*\") (before you did @PowerMockIgnore(\"org.mypackage.\")).\n* @PrepareForTest now accepts wildcards in the fullyQualifiedName attribute, e.g. you can now do @PrepareForTest(fullyQualifiedName={\"*name*\"}) to prepare all classes in containing \"name\" in its fully-qualified name.\n* Fixed a major issue with the prepare for test algorithm. Before classes were accidentally prepared for test automatically if the fully qualified name of the class started with the same fully qualified name as a class that were prepared for test. This has now been resolved. This may lead to backward incompatibility issues in cases where tests didn't prepare all necessary artifacts for test.\n* Mockito extension API now supports verification of private methods (for both static and instance methods). Use verifyPrivate(..).invoke(..), e.g. verifyPrivate(myObject, times(2)).invoke(\"myMethod\", argument1, argument2).\n* Verification behavior of static method in the Mockito extension API has changed. Before you did \"verifyStatic(MyClass.class); MyClass.methodToVerify(argument);\", now you do \"verifyStatic(); MyClass.methodToVerify(argument);\". You can also pass a verification mode when verifying static methods: \"verifyStatic(times(2)); MyClass.methodToVerify(argument);\". This change is NOT backward compatible with version 1.2.5.\n* Mockito extension API now supports \"verifyNoMoreInteractions\" and \"verifyZeroInteractions\" for both instance mocks, class mocks and new instance mocks.\n* Deprecated setSubstituteReturnValues, getSubstituteReturnValues and addSubtituteReturnValue in MockPolicyInterceptionSettings, you should now use setMethodsToStub, getStubbedMethods and stubMethod instead.\n* Renamed MockRepository#getSubstituteReturnValue to getMethodToStub and MockRepository#putSubstituteReturnValue to putMethodToStub.\n* PowerMockito now supports, doAnswer, doThrow, doCallRealMethod, doNothing and doReturn for void methods defined in final classes, final void methods and static methods. Note that if a method is a private void method you should still use PowerMockito#when.\n* Removed the deprecated classes \"org.powermock.PowerMock\" and \"org.powermock.Whitebox\".\n* PowerMock support API now has a DeepCloner class that you can use to create a clone of an object. This clone can also be cloned to a different classloader.\n* Added a PowerMock classloading project which can be used to execute any Runnable or Callable in a different classloader. The result of a callable operation will be cloned to the the callers classloader.\n* Mocking static methods in final system classes works in the Mockito extension API.\n* AnnotationEnablers only injects to fields that haven't previously been set (i.e. if the field is null).\n* Added org.powermock.core.spi.listener.AnnotationEnablerListener interface that all AnnotationEnablers must implement.\n* Implemented a fluent API for suppression, replacing and stubbing (org.powermock.api.support.membermodification.MemberModifier). It uses matcher methods defined in org.powermock.api.support.membermodification.MemberMatcher. Some examples:\n        replace(method(X)).with(method(Y)); // Works only for static methods\n\treplace(method(X)).with(invocationHandler); \n\tstub(method(X)).andReturn(Y);\n\tsuppress(methodsDeclaredIn(X.class, Y.class))\n\tsuppress(method(X.class, \"methodName\"))\n\tsuppress(methods(method(X.class, \"methodName\"), method(Y.class, \"methodName2\")))\n\tsuppress(methods(X.class, \"methodName1\", \"methodName2\"))\n\tsuppress(field(..))\n\tsuppress(constructor(..));\n* Deprecated all suppressMethod, suppressField and suppressConstructor methods in the EasyMock extension API. You should now use PowerMock#suppress instead.\n* PowerMock and PowerMockito now supports stubbing methods (including private methods). Use PowerMock#stub or PowerMockito#stub to accomplish this.\n* PowerMock and PowerMockito now supports proxying methods, including private methods using replace(..), e.g. replace(method(MyClass.class, \"methodToProxy\")).with(myInvocationHandler). Every call to the \"methodToProxy\" method will be routed to the supplied invocation handler instead.\n* PowerMock and PowerMockito now supports duck typing of static methods, including static private methods using replace(..), e.g. replace(method(MyClass.class, \"methodToDuckType\")).with(method(MyOtherClass.class, \"methodToInvoke\")). Every call to the \"methodToDuckType\" method will be routed to the \"methodToInvoke\" method instead.\n* Mock policies now supports proxing methods using proxyMethod(..).\n* Private inner memeber interfaces are not changed to public anymore during the byte-code manipulation session\n* PowerMock JUnit4 Runner can now instantiate test classes that have a String constructor if the test class extends from junit.framework.TestCase.\n\nChange log 1.2.5 (released 2009-05-05)\n--------------------------------------\n* Mocking of static methods in final system classes such as java.lang.System now works. To do this you need to prepare the class that invokes the method of the system class as well as the actual test case.\n* Fixed a major issue with mock policies which caused them to fail if a test case had more than one test method. Also fixed so that mock policies works in \"setup\" methods.\n* Fixed so that WhiteboxImpl#getMethod no longer fails when invoking proxified interface methods declared in extended interfaces. Previously if e.g. interface A extended B & C and a method was declared in B it wouldn't be found by WhiteboxImpl#getMethod since it only used to traverse the class hierarchy and not the structure of the extended interfaces.\n* Whitebox#invokeMethod now works without specifying any method name which can increase the refactoring possibilities of the code when invoking unique private methods.\n* Fixed the error message when a method couldn't be found and only one method was specified (for example when using Whitebox.getMethods(MyClass.class, \"onlyOneMethod\")).\n* All field matcher strategies now throws FieldNotFoundException's instead of IllegalArgumentException's.\n* Upgraded the Mockito API extension to use Mockito 1.7.\n* Added mockPartial and mockStaticPartial to the Mockito API to allow for easier creation of partial mocks.\n\nChange log 1.2 (released 2009-01-30)\n------------------------------------\n* Upgraded to Javassist 3.9\n* The test result related artifacts were moved from package org.powermock.tests.result to org.powermock.core.spi.testresult.\n* Structural refactoring to remove Structure 101 XS: Moved org.powermock.api.easymock.internal.proxyframework.spi.ProxyFramework to org.powermock.reflect.internal.proxy.ProxyFramework.\n* Added PowerMock specific exceptions to the reflect project. Instead of getting RuntimeExceptions or IllegalArgument exceptions a more appropriate runtime exception is thrown. For example ConstructorNotFoundException or TooManyFieldsFoundException etc.\n* Whitebox.getMethods(..) and Whitebox.getFields(..) now throw an MethodNotFoundException if no method or field was found.\n* Error messages when expecting new now works correctly for inner classes.\n* Added three new methods to the Whitebox class, these are Whitebox.getInnerClassType(..), Whitebox.getLocalClassType(..) and Whitebox.getAnonymousInnerClassType(..). These methods helps with getting the class type for private inner, local or anonymous inner classes.\n* Inner member classes declared in class X are automatically prepared for test when X is prepared for test.\n* PowerMock now follows the semantics of EasyMock verification. This means that invoking an unexpected method of a mock object will cause an AssertionError to be thrown even if verify has been called prior to the method invocation.\n* Interfaces will now be bytecode manipulated if included in @PrepareForTest or @SuppressStaticInitializationFor. This is useful since interfaces can also contain evil static initializers (using bytecode manipulation or other tricks). Concrete example found in XMLBeans.\n* Fixed problem with infinite recursion with some hashCode implementations\n* Possible to mock non-final system classes such as java.net.URLEncoder. To do this you need to prepare the class that invokes the method of the system class as well as the actual test case.\n* Fixed a NPE bug in WhiteboxImpl#findSingleFieldUsingStrategy when the startClass was null and a field name haven't been found.\n\nChange log 1.1.1 (released 2008-12-15)                                                                     \n--------------------------------------\n* Fixed maven version issues for the junit4-legacy module and junit3 module.\n* Fixed a major issue with PowerMock test listeners. The PowerMockTestListener.beforeTestMethod(..) was invoked too late which could cause a NullPointerException when invoking setup methods.\n* Updated javadoc (some errors in the java doc text).\n\nChange log 1.1 (released 2008-12-12)\n------------------------------------\n* Only signed classes are loaded by the signed supporting CGLib naming policy.\n* Whitebox.invokeConstructor now propagates InvocationTargetExceptions correctly.\n* Restructured release assemblies to include just the correct things.\n* Set sources:jar and javadocs:jar to run on every build.\n* LoggerTest now creates its test log file in ./target/ directory instead of ./\n* Major refactoring of project structure, it's now be possible to use PowerMock as a foundation for testability for other mock frameworks. PowerMock core is no longer coupled to EasyMock.\n* Fixed a serious issue with the classloading hierarchy of PowerMock's JUnit runners.\n* Implemented support for PowerMock test listeners, to create a listener you need to implement the org.powermock.core.spi.PowerMockTestListener interface and pass the implementation class to the PowerMockListener annotation.\n* Started Mockito integration. It supports final, static (non-void) and partial mocking using the PowerMock Mockito API. It also supports the Mockito annotations if using the @PowerMockListener(AnnotationEnabler.class) at the class-level of the test case.\n* Added a new Mock annotation which can be placed on fields to allow for a PowerMock listener to create and inject mock objects. Use the AnnotationEnabler listener from the EasyMock or Mockito API.\n* Exceptions are no longer wrapped in run-time exceptions when invoking a method using Whitebox.invokeMethod(..).\n* Major refactoring of the classloader structure and delegation.\n* Added two new methods to the Whitebox API, getAllInstanceFields and getAllStaticFields. One takes an object as parameter and one takes a class. They return all instance/class fields of the object/class. \n* Added a FieldDefaulter test listeners that set all instance field to their default value after each test method. This listener can be used to automatically set all instances to null after each test method instead of doing so manually in a tearDown method.\n* Added three new methods to the PowerMock API, reset(Object...mocks), reset(Class<?>...classMocks) and resetAll(). The methods can be used to reset instance mocks, class mocks or let PowerMock reset all mocks automatically.\n* mockStaticNice(Class<?> clazz, String... methodNames) was renamed to mockStaticPartialNice in the PowerMock API.\n* PowerMock and PowerMockito now _really_ follows the EasyMock semantics for partial mocking (e.g. PowerMock.createMock(MyClass.class, null) now mocks all methods of a class whereas PowerMock.createMock(MyClass.class, new Method[0]) mocks no methods of a class).\n* The @PrepareForTest annotation now accepts interfaces as types. This is useful in situations where you wan't to make sure that a certain interface is loaded by the same classloader as the rest of the mocks.\n* Updated the tutorial projects to reflect the latest changes in PowerMock.\n* Errors are propagated correctly when invoking the PowerMock.replay(..) method (i.e. they are no longer wrapped in run-time exceptions).\n* Added a MockNice and MockStrict annotation which can be placed on fields to allow for the AnnotationEnabler of the EasyMock api to create and inject mock objects.\n* Changed so that the default suppression value for methods returning java.lang.String is null to conform with EasyMock and Mockito.\n* Added Whitebox.getFieldsOfType(..) that can be used to retreive all fields of a particular type in a class hierarchy.\n* Added support for mock policies. A mock policy can be used to make it easier to unit test some code with PowerMock in isolation from a certain framework. Three mock policies are available in the EasyMock API, JclMockPolicy, Slf4jMockPolicy and Log4jMockPolicy which helps with mocking java commons-lang, log4j or slf4j in PowerMock. Use the @MockPolicy annotation at the class-level of the test case to use one of the mock policies.\n* Whitebox.getMethod(..) sets the accessable flag to true if a method is found.\n* Added Whitebox.getMethod(Class<?> type, Class<?>... parameterTypes) that let's you get a single method without specifying the method name.\n* Fixed a bug in WhiteboxImpl.checkIfTypesAreSame(..) that prevented classes to be identified correctly.\n* Fixed a bug in the PowerMockJUnit44RunnerDelegateImpl that caused a NoClassDefFoundError to be thrown when using JUnit 4.5 when a AssumptionViolatedException was thrown. The reason for this was that JUnit has changed to locatation of this exception.\n* Added spy functionality of final classes and methods to the Mockito API (experimental).\n* Fixed so that it works to place the PrepareForTest annotation at methods without specifying it at the class-level first.\n* Added Whitebox.getField(..) method to get a field somewhere in the hierarchy.\n* Added Whitebox.getFields(..) method to get fields in a class matching a specific name.\n* Added methods to the PowerMock API, PowerMock.suppressField(..), that allows to suppress specific fields of a class (no support for primitive final fields right now).\n* Deprecation: org.powermock.PowerMock and org.powermock.Whitebox have been deprecated, you should now use org.powermock.api.easymock.PowerMock and org.powermock.reflect.Whitebox instead.\n\nChange log 1.0 (released 2008-11-18)\n------------------------------------\n* Changed the pom.xml for the tutorial project so that it's now a stand-alone project.\n* Fixed so that replay all and verify all also works for createMockAndExpectNew.\n* Added method createStrictMockAndExpectNew and createNiceMockAndExpectNew\n* Fixed so that suppressMethodCode returns an empty string for methods returning String. \n* Fixed a bug in the byte-code manipulation of constructors, modifiers that doesn't need change are now preserved.\n* Added the PrepareEverythingForTestAnnotation, this annotation can be used to tell PowerMock to modify all classes.\n* MockGateway doMethodCall now also supports java proxy types.\n* Implemented the ability to set and get internal state based on field type. This means that you get more refactor friendly code while still being able to set or get internal state.\n* Implemented the ability to set internal state based on an object type, i.e. you can now do setInternalState(object, myServiceImpl) to set the first field in object which can be assignable to myServiceImpl. This means that you get more refactor friendly code while still being able to set internal state.\n* Get and setInternalState now separates between class and instance fields, i.e. you cannot set static fields by specifying an instance object.\n* Updated the tutorial projects to take advantage of the latest features in PowerMock.\n* Fixed a NPE bug in the AbstractTestClassExtractor.isPrepared(..) method.\n* The test class is no longer recommended as a PrepareForTest candidate if a NPE occurs inside the test class.\n* Added createStrictPartialMockForAllMethodsExcept and createNicePartialMockForAllMethodsExcept to the PowerMock API.\n* The Whitebox API method getAllMethodExcept now traverses the class hierarchy looking for methods.\n* Fixed a bug in the verifyAll method of the PowerMock API, the state is now properly disposed.\n* Verify now only clears state of the artifact being verified, this means that you use sequential verify statements again. However you must always use a PowerMockRunner in order to make sure that the full state is properly disposed.\n* The suppressConstructorCode method of the PowerMock API was renamed to suppressConstructor.\n* The suppressMethodCode method of the PowerMock API was renamed to suppressMethod. \n* The suppressConstructorCodeHierarchy method of the PowerMock API was removed, suppressConstructor(..) automatically suppress the full hierarchy so use this method instead.\n* Added the PowerMockIgnore annotation that can be used to specify packages or classes that should not be loaded by PowerMock's classloader.\n* Fixed a bug in MockGateway that prevented wrapper/primitive constructors from being correctly executed.\n* Added support for specifying parameter types for expectNew and createMockAndExpectNew, createNiceMockAndExpectNew, createStrictMockAndExpectNew.\n* Added expectNiceNew and expectStrictNew, expectNiceNew can be used with no parameters.\n* Internal refactoring of the chunking mechanism\n* Fixed a bug in the chunking algorithm that made the test listener clear state for all class loaders even though it should only clear the state for the last one. Fixed this for JUnit4 and JUnit3.\n\nChange log 0.9 (released 2008-11-10)\n------------------------------------\n* Structural refactoring to remove Structure 101 XS: moved WhiteBox implementation to separate class in core and moved IndicateReloadClass\n* By default Whitebox.getInternalState and Whitebox.setInternalState now traverses the class hierarchy when looking for a field.\n* Better error message if a NPE is caught in a subclass of a class being prepared for test.\n* The PrepareForTest annotation now manipulates the full (super) class hierachy by default. This makes it easier to perform mocking of super class methods.\n* A new annotation called PrepareOnlyThisForTest has been added and works in the same way that PrepareForTest previously did, i.e. ONLY the specified classes are prepared and not the entire hierarchy.\n* Fixed a bug that made it impossible to invoke vararg constructors.\n* createMockAndExpectNew now takes expected arguments as the second parameter.\n* expectNew takes expected arguments as the second parameter.\n* Invocations of var arg methods, constructors and expectPrivate now works for sub-types of the declared parameter types.\n* More consistent error messages when expectNew fails. Error messages now takes the parameters into account.\n* Renamed mockStaticMethodX to mockStaticPartialX\n* Added javadoc to the release phase\n* The JUnit4 legacy runner now throws NoTestsRemainException if no tests are found in the test case. \n* All JUnit4 runners now executes the setUp method before each test and the tearDown method after each test if the test class extends from TestCase.\n* Fixed an issue in the getAllChunkEntries method of the AbstractTestSuiteChunkerImpl class that caused test methods to be executed in a different order when running in a test suite than running the test stand alone.\n* Fixed a serious issue when the suppress static constructor state disappeared between chunking sessions. Fixed this for all versions of JUnit 4. This means that chunking and suppression of static initializers now work as expected.\n* The PowerMock API methods with a syntax like createPartialMockX are renamed to createXPartialMock, e.g. createPartialMockNice is renamed to createNicePartialMock to be more consistent with the normal createMock methods.\n* Added createNicePartialMockAndInvokeDefaultConstructor and createStrictPartialMockAndInvokeDefaultConstructor to the PowerMock API.\n* Updated the tutorial projects with\n* Changed the clean-up mechanisms of PowerMock.replay(..) and PowerMock.verify(..). Should no longer clear unnecessary state.\n* Implemented two new PowerMock API methods: replayAll and verifyAll(). These can be used to replay and verify all classes and mocks created by the PowerMock API without having to explicitly specify each and everyone.\n\nChange log 0.8.5 (releasd 2008-10-30)\n-------------------------------------\n* Fixed so that it's now possible to mock abstract methods\n* WhiteBox.getMethod(..) now also returns protected and package-private methods.\n* Whitebox.invokeMethod can now execute methods in a super class.\n* Whitebox.invokeMethod no longer throws NullPointerException when an argument is null when the method cannot be found\n* It's is now possible to use sub-types of method parameters when using Whitebox.invokeMethod.\n* Tests methods starting with \"test\" are now executed only if the method is annotated with @Test or if the test class extends from TestCase.\n* Tests are now executed in the order that they are defined in the test case.\n                                                                            \nChange log 0.8.1 (released 2008-10-26)\n--------------------------------------\n* Added PowerMock API method \"createPartialMockAndInvokeDefaultConstructor\" that invokes a default constructor after mock creation (even if it's private).\n* createPartialMock now works as expected\n* Fixed so that it works to mock package private classes (even if they're signed)\n* It now works to set a static final field after the static initializes have been suppressed.\n* Fixed a serious bug that caused classes extending java.lang.Object to be non-mockable.\n                                                                                           \nChange log 0.8 (released 2008-10-22)\n-----------------------------------\n* The junit4 test module now work with JUnit 4.5 (although using the old, now deprecated, approach of JUnit 4.4).\n* Upgraded to EasyMock 2.4\n* Upgraded to JavaAssist 3.8.0.GA\n* WhiteBox invoke method and invoke constructor methods now throws an IllegalArgumentException if the first argument is null.\n* Replay/verify works as expected when mixing classes and instance mocks.\n* Better error message when expectNew fails due to too few calls to new when a method was invoked using reflection.\n* Implemented support for nice mocks.\n* Added more documentation\n* expectNew(..).andThrow(..) now works with checked exceptions\n* Added WhiteBox functionality to instantiate a class without invoking its constructor without using byte-code manipulation. Works in multiple JVM's.\n* mockMethodX is renamed to createPartialMockX        \n* Fixed the error message that was thrown when a constructor was not found when using mocks as arguments with createPartialMock.\n* Suppress constructor code now works as expected\n* mockConstruction(..) was removed. You should always use expectNew(..) instead. There's a utility method in PowerMock called createMockAndExpectNew that can be used as a substitute for mockConstruction(..). \n* Better error message when a class is not replayed when doing expectNew.\n* Added support to easy suppress several methods in the same class.\n* doInvokeMethod in PowerMock now catches and deals correctly with InvocationTargetExceptions.\n* It's now possible to run a single test case in junit4\n* Test delegates now implements Sortable\n* Added support for mocking classes in signed jar files\n* EasyMock matchers now works in combination with PowerMock's expectPrivate(..)\n* Added support for invoking var args constructors and methods using Whitebox\n* Added support for expecting private methods with var args parameter\n* PowerMock now supports Hamcrest matchers\n* Exceptions are now propagated correctly from the junit runners.\n                             \nChange log 0.7 (released)\n-------------------------\n* Do not mock hashCode and equals\n* Added ugly hack for cglib classloading issue with maven\n* Fixed problems with mocking methods in superclass and modifying multiple classes with same parent\n* Strict mocking with interface work as expected\n* Added niceReplayAndVerify\n* Added logo and improved documentation structure\n* Follow EasyMock semantics for partial mocking\n* WhiteBox internalstate support for static fields as expected\n* Updated assembly and create sources jar files\n\nChange log 0.6 (released)\n-------------------------\n* Updated to EasyMock 2.3 and classextension 2.3\n* Implemented support for ConstructorArgs\n* Implemented support for StrictMock\n* Added possibility to invoke a private method in a subclass of an instance using Whitebox.\n* Added a support for test classes extending from TestCase when using a custom JUnit runner such as PowerMockRunner. This fix was created for both JUnit4 legacy and JUnit 4.4. \n* Major internal refactoring.\n* Fixed major classloading and byte-code manipulation issues. Code coverage tools such as EMMA now works.\n* Fixed so that it's now possible to invoke private methods using non-primitive and/or non-wrapper values.\n* Whitebox now throws the correct exceptions to the client and not a wrapped RuntimeException. This means for example that expectNew(..).andThrow(..) works as expected.\n* Fixed a bug in the PowerMock JUnit 4.4 and legacy runner that reported back the wrong number of tests being executed when @Ignore was used. \n"
  },
  {
    "path": "docs/generate_javadoc.sh",
    "content": "#!/bin/sh\nread -p \"Version to generate javadoc for: \" version\nproject_names=(powermock-core powermock-api-easymock powermock-api-mockito powermock-api-mockito2 powermock-api-mockito-common\\\n powermock-reflect powermock-api-support powermock-module-junit4-common powermock-module-junit4 powermock-module-junit4-rule\\\n powermock-classloading-module powermock-classloading-xstream powermock-module-javaagent powermock-module-junit4-rule-agent\\\n powermock-module-junit3 powermock-module-junit4-legacy powermock-module-testng-common powermock-module-testng\\\n powermock-module-testng-agent powermock-modules-impl powermock-classloading-objenesis)\n\necho \"Generating Javadoc for version ${version}.\"\n\nfor project_name in ${project_names[*]}\ndo\n\techo \"Generating for ${project_name}\"\n    curl -Ss http://www.javadoc.io/doc/org.powermock/${project_name}/${version} >/dev/null 2>&1\ndone\necho \"Completed\"\n\n"
  },
  {
    "path": "docs/release-notes/official.md",
    "content": "<sup><sup>*Release notes were automatically generated by [Shipkit](http://shipkit.org/)*</sup></sup>\n\n#### 2.0.9\n - 2020-11-01 - [4 commits](https://github.com/powermock/powermock/compare/powermock-2.0.8...powermock-2.0.9) by [thekingn0thing](https://github.com/thekingn0thing) (2), [Valery Yatsynovich](https://github.com/valfirst) (1), [zaobao](https://github.com/zaobao) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.9-green.svg)](https://bintray.com/powermock/null/powermock/2.0.9)\n - PowerMockitoStubberImpl.when throws exceptions with methods using arguments with both primitive and wrapped arguments [(#1077)](https://github.com/powermock/powermock/pull/1077)\n - Bump byte-buddy from 1.9.10 to 1.10.14 [(#1068)](https://github.com/powermock/powermock/pull/1068)\n\n#### 2.0.8\n - 2020-11-01 - [6 commits](https://github.com/powermock/powermock/compare/powermock-2.0.7...powermock-2.0.8) by 4 authors - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.8-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.8)\n - Commits: Sean C. Sullivan (2), [Valery Yatsynovich](https://github.com/valfirst) (2), dependabot[bot] (1), [Improver](https://github.com/netbeansuser2019) (1)\n - [Travis CI] Remove deprecated keyword `sudo` [(#1069)](https://github.com/powermock/powermock/pull/1069)\n - Upgrade [(#1049)](https://github.com/powermock/powermock/pull/1049)\n\n#### 2.0.7\n - 2020-03-30 - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.6...powermock-2.0.7) by [Björn Kautler](https://github.com/Vampire) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.7-green.svg)](https://bintray.com/powermock/null/powermock/2.0.7)\n - [Bugfixes] PowerMock Agent does not work EasyMock 4.x [(#956)](https://github.com/powermock/powermock/issues/956)\n - Fix missing stackmap frames [(#1043)](https://github.com/powermock/powermock/pull/1043)\n - VerifyError using the agent for Spock tests [(#1005)](https://github.com/powermock/powermock/issues/1005)\n - Update dependencies for Java 11 support [(#952)](https://github.com/powermock/powermock/pull/952)\n - How to resolve \"Expected stackmap frame at this location\" [(#693)](https://github.com/powermock/powermock/issues/693)\n\n#### 2.0.6\n - 2020-03-21 - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.5...powermock-2.0.6) by [Valery Yatsynovich](https://github.com/valfirst) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.6-green.svg)](https://bintray.com/powermock/null/powermock/2.0.6)\n - Upgrade to Javassist 3.27.0-GA [(#1041)](https://github.com/powermock/powermock/pull/1041)\n\n#### 2.0.5\n - 2020-01-25 - [5 commits](https://github.com/powermock/powermock/compare/powermock-2.0.4...powermock-2.0.5) by [Enrico Olivelli](https://github.com/eolivelli) (3), [thekingn0thing](https://github.com/thekingn0thing) (2) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.5-green.svg)](https://bintray.com/powermock/null/powermock/2.0.5)\n - Use Unsafe to set final static fields, support JDK12+ [(#1026)](https://github.com/powermock/powermock/pull/1026)\n - Enable local build in IDE without setting ENV [(#1025)](https://github.com/powermock/powermock/pull/1025)\n\n#### 2.0.4\n - 2019-10-16 - [8 commits](https://github.com/powermock/powermock/compare/powermock-2.0.2...powermock-2.0.4) by 5 authors - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.4-green.svg)](https://bintray.com/powermock/null/powermock/2.0.4)\n - Commits: [Arthur Zagretdinov](https://github.com/thekingnothing) (3), [Björn Kautler](https://github.com/Vampire) (2), [Johan Haleby](https://github.com/johanhaleby) (1), [Kirill Baurchanu](https://github.com/baurchanu) (1), sam-ma (1)\n - [Bugfixes] Not compatible with JUnitParams when using @PowerMockRunnerDelegate(JUnitParamsRunner.class [(#685)](https://github.com/powermock/powermock/issues/685)\n - Fix Whitebox.getAllInstanceFields returning static fields for classes [(#1011)](https://github.com/powermock/powermock/pull/1011)\n - Fix changing final fields on Java 12 [(#1010)](https://github.com/powermock/powermock/pull/1010)\n - Fixes #685 : @PowerMockRunnerDelegate(JUnitParamsRunner.class) [(#998)](https://github.com/powermock/powermock/pull/998)\n - Fixes #992 Static mocking broken for Mockito >= 2.26.1 [(#997)](https://github.com/powermock/powermock/pull/997)\n\n#### 2.0.2\n - 2019-04-21 - [2 commits](https://github.com/powermock/powermock/compare/powermock-2.0.1...powermock-2.0.2) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.2-green.svg)](https://bintray.com/powermock/null/powermock/2.0.2)\n - Fixes #979 Generalise getting current java version to fix be able to use Javaagent with latest java [(#985)](https://github.com/powermock/powermock/pull/985)\n - Fixes #973 [SECURITY] Releases are built/executed/released in the context of insecure/untrusted code [(#984)](https://github.com/powermock/powermock/pull/984)\n - PowerMockAgent does not support java >=10 [(#979)](https://github.com/powermock/powermock/issues/979)\n - [SECURITY] Releases are built/executed/released in the context of insecure/untrusted code [(#973)](https://github.com/powermock/powermock/issues/973)\n\n#### 2.0.1\n - 2019-04-21 - [4 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0...powermock-2.0.1) by 4 authors - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.1-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.1)\n - Commits: [Arthur Zagretdinov](https://github.com/thekingnothing) (1), [Marcin Zajączkowski](https://github.com/szpak) (1), [sam-ma](https://github.com/sam-ma) (1), [stevegilbert23](https://github.com/stevegilbert23) (1)\n - [Bugfixes] IllegalStateException when inner class has private constructor on Java>8 [(#958)](https://github.com/powermock/powermock/issues/958)\n - Fixes #958 convert constructors of nested classes to public as well [(#978)](https://github.com/powermock/powermock/pull/978)\n - Fixes 976: Change to StackTraceCleaner to allow mockito strick stubs … [(#977)](https://github.com/powermock/powermock/pull/977)\n - Fix date in README [(#967)](https://github.com/powermock/powermock/pull/967)\n\n#### 2.0.0\n - 2019-01-07 - [77 commits](https://github.com/powermock/powermock/compare/powermock-1.7.3...powermock-2.0.0) by 10 authors - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-green.svg)](https://bintray.com/powermock/null/powermock/2.0.0)\n - Commits: [Arthur Zagretdinov](https://github.com/thekingnothing) (56), PowerMock Release Tools (11), [Henri Tremblay](https://github.com/henri-tremblay) (2), [Ismael Juma](https://github.com/ijuma) (2), beegee1 (1), [Enrico Olivelli](https://github.com/eolivelli) (1), hsynkrtl (1), [Paul Parenko](https://github.com/parenko) (1), Sean Gilhooly (1), [Timo Meinen](https://github.com/timomeinen) (1)\n - [Major changes] Mockito Public API Support Roadmap  [(#726)](https://github.com/powermock/powermock/issues/726)\n - [Bugfixes] Compile error due to unused import of a class which is not in the dependencies [(#959)](https://github.com/powermock/powermock/issues/959)\n - [Bugfixes] JDK9, power mockito 2.0.0-beta.5 - final class issue when mocking static method [(#888)](https://github.com/powermock/powermock/issues/888)\n - [Bugfixes] @Mock annotation from easymock api does not work for two fields of the same type. [(#755)](https://github.com/powermock/powermock/issues/755)\n - [Enhancements] Removed deprecated code in PowerMock 2.0.  [(#839)](https://github.com/powermock/powermock/issues/839)\n - [Enhancements] JDK 9 support [(#783)](https://github.com/powermock/powermock/issues/783)\n - Fixes #888: Disable Security of X-Stream [(#962)](https://github.com/powermock/powermock/pull/962)\n - #959 fix compile error due to unused import of a class which is not i… [(#960)](https://github.com/powermock/powermock/pull/960)\n - Issue 939: Error with setInternalState and JDK12 \"java.lang.NoSuchFieldException: modifiers [(#955)](https://github.com/powermock/powermock/pull/955)\n - Remove MocksControl.MockType that stayed there [(#951)](https://github.com/powermock/powermock/pull/951)\n - Preparing PowerMock 2.0 Release without ByteBuddy [ci maven-central-release] [(#948)](https://github.com/powermock/powermock/pull/948)\n - Use EasyMock exposed MockType instead of the deprecated internal one [(#944)](https://github.com/powermock/powermock/pull/944)\n - Powermock migration to ByteBuddy [(#910)](https://github.com/powermock/powermock/pull/910)\n - Update PowerMockAgent.java [(#878)](https://github.com/powermock/powermock/pull/878)\n\n#### 2.0.0-RC.5\n - 2018-12-25 - [2 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-RC.4...powermock-2.0.0-RC.5) by [Paul Parenko](https://github.com/parenko) (1), [Timo Meinen](https://github.com/timomeinen) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-RC.5-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-RC.5)\n - [Bugfixes] Compile error due to unused import of a class which is not in the dependencies [(#959)](https://github.com/powermock/powermock/issues/959)\n - [Bugfixes] JDK9, power mockito 2.0.0-beta.5 - final class issue when mocking static method [(#888)](https://github.com/powermock/powermock/issues/888)\n - Fixes #888: Disable Security of X-Stream [(#962)](https://github.com/powermock/powermock/pull/962)\n - #959 fix compile error due to unused import of a class which is not i… [(#960)](https://github.com/powermock/powermock/pull/960)\n\n#### 2.0.0-RC.4\n - 2018-11-17 - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.0-RC.3...powermock-2.0.0-RC.4) by [Enrico Olivelli](https://github.com/eolivelli) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-RC.4-green.svg)](https://bintray.com/powermock/null/powermock/2.0.0-RC.4)\n - Issue 939: Error with setInternalState and JDK12 \"java.lang.NoSuchFieldException: modifiers [(#955)](https://github.com/powermock/powermock/pull/955)\n\n#### 2.0.0-RC.3\n - 2018-11-07 - [2 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-RC.2...powermock-2.0.0-RC.3) by beegee1 (1), [Ismael Juma](https://github.com/ijuma) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-RC.3-green.svg)](https://bintray.com/powermock/null/powermock/2.0.0-RC.3)\n - No pull requests referenced in commit messages.\n\n#### 2.0.0-RC.2\n - 2018-10-28 - [2 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-RC.1...powermock-2.0.0-RC.2) by [Arthur Zagretdinov](https://github.com/thekingnothing) (1), [Henri Tremblay](https://github.com/henri-tremblay) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-RC.2-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-RC.2)\n - Remove MocksControl.MockType that stayed there [(#951)](https://github.com/powermock/powermock/pull/951)\n\n#### 2.0.0-RC.1\n - 2018-10-24 - [69 commits](https://github.com/powermock/powermock/compare/powermock-1.7.4...powermock-2.0.0-RC.1) by 6 authors - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-RC.1-green.svg)](https://bintray.com/powermock/null/powermock/2.0.0-RC.1)\n - Commits: [Arthur Zagretdinov](https://github.com/thekingnothing) (54), PowerMock Release Tools (11), [Henri Tremblay](https://github.com/henri-tremblay) (1), hsynkrtl (1), [Ismael Juma](https://github.com/ijuma) (1), Sean Gilhooly (1)\n - [Major changes] Mockito Public API Support Roadmap  [(#726)](https://github.com/powermock/powermock/issues/726)\n - [Bugfixes] @Mock annotation from easymock api does not work for two fields of the same type. [(#755)](https://github.com/powermock/powermock/issues/755)\n - [Enhancements] Removed deprecated code in PowerMock 2.0.  [(#839)](https://github.com/powermock/powermock/issues/839)\n - [Enhancements] JDK 9 support [(#783)](https://github.com/powermock/powermock/issues/783)\n - Preparing PowerMock 2.0 Release without ByteBuddy [ci maven-central-release] [(#948)](https://github.com/powermock/powermock/pull/948)\n - Use EasyMock exposed MockType instead of the deprecated internal one [(#944)](https://github.com/powermock/powermock/pull/944)\n - Powermock migration to ByteBuddy [(#910)](https://github.com/powermock/powermock/pull/910)\n - Update PowerMockAgent.java [(#878)](https://github.com/powermock/powermock/pull/878)\n\n**2.0.0-beta.13 (2018-10-22)** - no code changes (no commits) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.13-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.13)\n\n**2.0.0-beta.12 (2018-10-22)** - [2 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.11...powermock-2.0.0-beta.12) by [Arthur Zagretdinov](https://github.com/thekingnothing) (1), [Henri Tremblay](https://github.com/henri-tremblay) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.12-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.12)\n - Use EasyMock exposed MockType instead of the deprecated internal one [(#944)](https://github.com/powermock/powermock/pull/944)\n\n**2.0.0-beta.11 (2018-05-29)** - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.10...powermock-2.0.0-beta.11) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.11-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.11)\n - No pull requests referenced in commit messages.\n\n**2.0.0-beta.10 (2018-05-29)** - [20 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.9...powermock-2.0.0-beta.10) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.10-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.10)\n - Powermock migration to ByteBuddy [(#910)](https://github.com/powermock/powermock/pull/910)\n\n**2.0.0-beta.9 (2018-04-08)** - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.8...powermock-2.0.0-beta.9) by Ismael Juma - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.9-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.9)\n - No pull requests referenced in commit messages.\n\n**2.0.0-beta.8 (2018-03-20)** - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.7...powermock-2.0.0-beta.8) by Sean Gilhooly - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.8-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.8)\n - No pull requests referenced in commit messages.\n\n**2.0.0-beta.7 (2018-03-12)** - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.6...powermock-2.0.0-beta.7) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.7-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.7)\n - No pull requests referenced in commit messages.\n\n**2.0.0-beta.6 (2018-03-12)** - [2 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.5...powermock-2.0.0-beta.6) by [Arthur Zagretdinov](https://github.com/thekingnothing) (1), hsynkrtl (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.6-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.6)\n - Update PowerMockAgent.java [(#878)](https://github.com/powermock/powermock/pull/878)\n\n**2.0.0-beta.5 (2017-09-17)** - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.4...powermock-2.0.0-beta.5) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.5-green.svg)](https://bintray.com/powermock/null/powermock/2.0.0-beta.5)\n - No pull requests referenced in commit messages.\n\n**2.0.0-beta.4 (2017-09-17)** - [4 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.3...powermock-2.0.0-beta.4) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.4-green.svg)](https://bintray.com/powermock/null/powermock-development/2.0.0-beta.4)\n - No pull requests referenced in commit messages.\n\n**2.0.0-beta.3 (2017-09-17)** - [1 commit](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.2...powermock-2.0.0-beta.3) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.3-green.svg)](https://bintray.com/thekingnothing/null/null/2.0.0-beta.3)\n - No pull requests referenced in commit messages.\n\n**2.0.0-beta.2 (2017-09-16)** - [4 commits](https://github.com/powermock/powermock/compare/powermock-2.0.0-beta.1...powermock-2.0.0-beta.2) by [Arthur Zagretdinov](https://github.com/thekingnothing) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.2-green.svg)](https://bintray.com/powermock/maven/powermock/2.0.0-beta.2)\n - [Bugfixes] @Mock annotation from easymock api does not work for two fields of the same type. [(#755)](https://github.com/powermock/powermock/issues/755)\n\n**2.0.0-beta.1 (2017-09-10)** - [35 commits](https://github.com/powermock/powermock/compare/powermock-1.7.1...powermock-2.0.0-beta.1) by [Arthur Zagretdinov](https://github.com/thekingnothing) (32), [Wojtek Wilk](https://github.com/wwilk) (2), PowerMock Release Tools (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.0.0-beta.1-green.svg)](https://bintray.com/powermock/maven/powermock/2.0.0-beta.1)\n - [Major changes] Mockito Public API Support Roadmap  [(#726)](https://github.com/powermock/powermock/issues/726)\n - [Enhancements] Removed deprecated code in PowerMock 2.0.  [(#839)](https://github.com/powermock/powermock/issues/839)\n - [Enhancements] Use Mockito Shipkit for CD [(#826)](https://github.com/powermock/powermock/issues/826)\n - Shipkit pom customizations [(#831)](https://github.com/powermock/powermock/pull/831)\n\n"
  },
  {
    "path": "gradle/java-module.gradle",
    "content": "repositories {\n    mavenLocal()\n    mavenCentral()\n    jcenter()\n}\n\ngroup = \"org.powermock\"\n\napply plugin: 'propdeps'\napply plugin: 'propdeps-maven'\napply plugin: 'java'\n\ntargetCompatibility = 1.6\nsourceCompatibility = 1.6\n\ntasks.withType(JavaCompile) {\n    options.warnings = false\n}\n\nif (JavaVersion.current() == JavaVersion.VERSION_1_8) {\n    apply plugin: 'checkstyle'\n    checkstyle {\n        toolVersion = checkstyleVersion\n        configFile = rootProject.file('config/checkstyle/checkstyle.xml')\n    }\n}\n\ntest{\n    exclude \"**/*Defect*\", \"**/*TestCase*\"\n}\n\n"
  },
  {
    "path": "gradle/modules.gradle",
    "content": "def publishableModules = allprojects - rootProject - project(\":powermock-api\") - project(\":powermock-classloading\") - project(\":powermock-modules\") - project(\":tests\") - project(\":tests\").subprojects - project(\":powermock-release\") - project(\":powermock-release\").subprojects\n\nconfigure(publishableModules) { project ->\n    apply from: \"${gradleScriptDir}/java-module.gradle\"\n    apply from: \"${gradleScriptDir}/publishing/publishable-module.gradle\"\n    apply from: \"${gradleScriptDir}/publishing/publish.gradle\"\n}\n\ndef skippedTasksForUnpublishableModules = [\n    'generatePomFileForJavaLibraryPublication',\n    'publishJavaLibraryPublicationToMavenLocal',\n    'javadoc',\n    'javadocJar',\n    'sourcesJar',\n    'bintrayUpload',\n    'install'\n]\n\ndef unpublishableModules = allprojects - publishableModules - project(\":powermock-release\").subprojects\nconfigure(unpublishableModules) { project ->\n    project.tasks.all {\n        if(skippedTasksForUnpublishableModules.contains(it.name)) {\n            it.enabled = false\n        }\n    }\n}\n\ndef skippedTasksForGenericModules = [\n    'generatePomFileForJavaLibraryPublication',\n    'publishJavaLibraryPublicationToMavenLocal',\n    'jar',\n    'javadoc',\n    'javadocJar',\n    'sourcesJar'\n]\n\ndef genericModules = project(\":powermock-release\").subprojects\nconfigure(genericModules) { project ->\n    project.tasks.all {\n        if (skippedTasksForGenericModules.contains(it.name)) {\n            it.enabled = false\n        }\n    }\n}\n\nif (project.hasProperty('checkJava6Compatibility') && !System.getenv(\"SKIP_RELEASE\")) {\n    //if we're skipping release, let's also skip checking compatibility (faster builds)\n    configure(publishableModules) { project ->\n        project.apply plugin: 'ru.vyarus.animalsniffer'\n        project.dependencies {\n            signature 'org.codehaus.mojo.signature:java16:1.0@signature'\n        }\n    }\n}\n\nproject(\":powermock-reflect\") {\n    description = \"Various utilities for accessing internals of a class.\"\n\n    dependencies {\n        compile(\"org.objenesis:objenesis:${objenesisVersion}\")\n        compile(\"net.bytebuddy:byte-buddy:${byteBuddy}\")\n        compile(\"net.bytebuddy:byte-buddy-agent:${byteBuddy}\")\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n        testCompile(\"cglib:cglib-nodep:${cglibVersion}\")\n    }\n}\n\nproject(\":powermock-core\") {\n    description = \"Various utilities for accessing internals of a class.\"\n\n    dependencies {\n        compile(project(\":powermock-reflect\"))\n        compile(\"org.javassist:javassist:${javassistVersion}\")\n        compile(\"net.bytebuddy:byte-buddy:${byteBuddy}\")\n        compile(\"net.bytebuddy:byte-buddy-agent:${byteBuddy}\")\n\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n        testCompile(\"com.github.stefanbirkner:system-rules:${systemRulesVersion}\")\n        testCompile(project(\":tests:utils\"))\n\n        testCompile(\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n    }\n}\n\nproject(\":powermock-api\") {\n    jar {\n        enabled = false\n    }\n}\n\nproject(\":powermock-api:powermock-api-support\") {\n    description = \"PowerMock API Utility classes.\"\n\n    dependencies {\n        compile(project(\":powermock-reflect\"))\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-api:powermock-api-easymock\") {\n    description = \"PowerMock API for EasyMock.\"\n\n    dependencies {\n        compile(project(\":powermock-api:powermock-api-support\"))\n        compile(\"cglib:cglib-nodep:${cglibVersion}\")\n        compile(\"org.easymock:easymock:${easymockVersion}\")\n\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\n\n\nproject(\":powermock-api:powermock-api-mockito2\"){\n    description = \"PowerMock API for Mockito 2.+..\"\n\n    dependencies {\n\n        compile(project(\":powermock-api:powermock-api-support\"))\n        compile(\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n\n        testCompile(project(\":tests:utils\"))\n    }\n}\n\nproject(\":powermock-classloading\") {\n    jar {\n        enabled = false\n    }\n}\n\nproject(\":powermock-classloading:powermock-classloading-base\") {\n    description = \"Utilities for loading and executing classes.\"\n\n    dependencies {\n        compile(project(\":powermock-api:powermock-api-support\"))\n        compile(project(\":powermock-reflect\"))\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-classloading:powermock-classloading-objenesis\") {\n    description = \"Performs classloader deep-cloning using Objenesis.\"\n\n    dependencies {\n        compile(project(\":powermock-classloading:powermock-classloading-base\"))\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-classloading:powermock-classloading-xstream\") {\n    description = \"Performs classloader deep-cloning using X-Stream.\"\n\n    dependencies {\n        compile(project(\":powermock-classloading:powermock-classloading-base\"))\n        compile(\"com.thoughtworks.xstream:xstream:${xstreamVersion}\")\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-modules\") {\n    jar {\n        enabled = false\n    }\n}\n\nproject(\":powermock-modules:powermock-module-javaagent\") {\n    description = \"PowerMock Java agent support.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n\n    jar {\n        manifest {\n            attributes(\n                    \"Manifest-Version\": \"1.0\",\n                    \"Premain-Class\": \"org.powermock.modules.agent.PowerMockAgent\",\n                    \"Agent-Class\": \"org.powermock.modules.agent.PowerMockAgent\",\n                    \"Can-Retransform-Classes\": true,\n                    \"Can-Redefine-Classes\": true\n            )\n        }\n    }\n}\n\nproject(\":powermock-modules:powermock-module-junit4-common\") {\n    description = \"PowerMock support module for all versions of JUnit 4.x.\"\n\n    dependencies {\n        compile(project(\":powermock-reflect\"))\n        compile(project(\":powermock-core\"))\n        compile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-modules:powermock-module-junit4\") {\n    description = \"PowerMock support module for JUnit 4.x.\"\n\n    dependencies {\n        compile(project(\":powermock-modules:powermock-module-junit4-common\"))\n        compile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n        testCompile(\"org.easymock:easymock:${easymockVersion}\")\n    }\n}\n\nproject(\":powermock-modules:powermock-module-junit4-legacy\") {\n    description = \"PowerMock support module for JUnit 4.0-4.3.\"\n\n    dependencies {\n        compile(project(\":powermock-modules:powermock-module-junit4-common\")) {\n            exclude group: 'junit', module: 'junit'\n        }\n        compile(\"junit:junit:4.3\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\n\nproject(\":powermock-modules:powermock-module-junit4-rule\") {\n    description = \"PowerMock support module for JUnit 4.x rules.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        compile(project(\":powermock-modules:powermock-module-junit4-common\"))\n\n        provided(project(\":powermock-classloading:powermock-classloading-base\"))\n\n        compile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\n\nproject(\":powermock-modules:powermock-module-junit4-rule-agent\") {\n    description = \"PowerMock support module for JUnit 4.x rules with Java agent\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        compile(project(\":powermock-modules:powermock-module-javaagent\"))\n\n        compile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-modules:powermock-module-testng-common\") {\n    description = \"PowerMock module for TestNG. Common classes\"\n\n    dependencies {\n        compile(project(\":powermock-reflect\"))\n        compile(project(\":powermock-core\"))\n        compile(\"org.testng:testng:${testngVersion}\")\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-modules:powermock-module-testng\") {\n    description = \"PowerMock module for TestNG.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        compile(project(\":powermock-modules:powermock-module-testng-common\"))\n        compile(\"org.testng:testng:${testngVersion}\")\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nproject(\":powermock-modules:powermock-module-testng-agent\") {\n    description = \"PowerMock module for TestNG with using Javaagent.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        compile(project(\":powermock-modules:powermock-module-testng-common\"))\n        compile(project(\":powermock-modules:powermock-module-javaagent\"))\n        compile(\"org.testng:testng:${testngVersion}\")\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n}\n\nconfigure(publishableModules) { project ->\n    apply from: \"${gradleScriptDir}/release/publish-jar.gradle\"\n\n}"
  },
  {
    "path": "gradle/publishing/publish-maven.gradle",
    "content": "apply plugin: 'maven-publish'\n\npublishing.publications.all {\n    def devs = ['johanhaleby:Johan Haleby:johan.haleby at jayway.com', 'jakr:Jan Kronquist:jan.kronquist at jayway.com', 'thekingnothing:Arthur Zagretdinov:arthur.zagretdinov at outlook.com']\n\n    pom.withXml {\n        def root = asNode()\n        root.remove(root.get('name'))\n        root.appendNode('name', 'PowerMock')\n\n        root.remove(root.get('url'))\n        root.appendNode('url', 'http://www.powermock.org')\n\n        root.remove(root.get('licenses'))\n        def license = root.appendNode('licenses').appendNode('license')\n        license.appendNode('name', 'The Apache Software License, Version 2.0')\n        license.appendNode('url', 'http://www.apache.org/licenses/LICENSE-2.0.txt')\n        license.appendNode('distribution', 'repo')\n\n        def developers = root.appendNode('developers')\n        devs.each {\n            def split = it.split(':')\n            assert split.length == 3\n            def d = developers.appendNode('developer')\n            d.appendNode('id', split[0])\n            d.appendNode('name', split[1])\n            d.appendNode('email', split[2])\n        }\n\n        root.dependencies.'*'.findAll() {\n            it.scope.text() == 'runtime' && project.configurations.compile.allDependencies.find { dep ->\n                dep.name == it.artifactId.text()\n            }\n        }.each() {\n            it.scope*.value = 'compile'\n        }\n\n        def depends\n        if (root.dependencies.size() > 0) {\n            depends = root.dependencies.get(0)\n        }else{\n            depends = root.appendNode('dependencies')\n        }\n\n        if (project.configurations.hasProperty('provided')) {\n            project.configurations.provided.allDependencies.each {\n                def dep = depends.appendNode('dependency')\n                dep.appendNode('groupId', it.group)\n                dep.appendNode('artifactId', it.name)\n                dep.appendNode('version', it.version)\n                dep.appendNode('scope', 'provided')\n            }\n        }\n\n        if (project.configurations.hasProperty('mockito2')){\n            project.configurations.mockito2.allDependencies.each {\n                def dep = depends.appendNode('dependency')\n                dep.appendNode('groupId', it.group)\n                dep.appendNode('artifactId', it.name)\n                dep.appendNode('version', it.version)\n                dep.appendNode('scope', 'compile')\n            }\n        }\n\n    }\n}\n\n\n"
  },
  {
    "path": "gradle/publishing/publish.gradle",
    "content": "bintray {\n    pkg {\n        repo = project.ext.bintrayRepo\n    }\n}\n\n\n"
  },
  {
    "path": "gradle/publishing/publishable-module.gradle",
    "content": "ext {\n    bintrayRepo = 'maven'\n    bintrayAutoPublish = true\n    mavenCentralSync = false\n    bintrayPublications = ['javaLibrary']\n}\n\njar {\n    manifest.attributes[\"Created-By\"] =\n            \"${System.getProperty(\"java.version\")} (${System.getProperty(\"java.specification.vendor\")})\"\n    manifest.attributes[\"Implementation-Title\"] = project.name\n    manifest.attributes[\"Implementation-Version\"] = project.version\n\n    from(\"${rootProject.projectDir}\") {\n        include \"LICENSE.txt\"\n        into \"META-INF\"\n        expand(copyright: new Date().format(\"yyyy\"), version: project.version)\n    }\n}\n\njavadoc {\n    description = \"Generates project-level javadoc for use in -javadoc jar\"\n\n    options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED\n    options.author = true\n    options.header = project.name\n    options.addStringOption('-quiet')\n\n    failOnError = false\n}\n\nartifacts {\n    archives sourcesJar\n    archives javadocJar\n}"
  },
  {
    "path": "gradle/release/distZip.gradle",
    "content": "def fullJars = [\n        project(\":powermock-release:powermock-easymock-junit\"),\n        project(\":powermock-release:powermock-easymock-testng\"),\n        project(\":powermock-release:powermock-mockito2-junit\"),\n        project(\":powermock-release:powermock-mockito2-testng\")\n]\n\nconfigure(fullJars) { project ->\n    ext {\n        bintrayRepo = 'generic'\n        bintrayAutoPublish = true\n        mavenCentralSync = false\n    }\n\n    repositories {\n        mavenCentral()\n        jcenter()\n    }\n\n    group = \"org.powermock\"\n\n    apply plugin: 'distribution'\n\n    distributions {\n        main {\n            contents {\n                from(project.configurations.compile)\n            }\n        }\n    }\n\n    apply from: \"${gradleScriptDir}/release/publish-distZip.gradle\"\n}\n"
  },
  {
    "path": "gradle/release/fullJars.gradle",
    "content": "def fullJars = [\n        project(\":powermock-release:powermock-easymock\"),\n        project(\":powermock-release:powermock-mockito2\")\n]\n\nconfigure(fullJars){ project ->\n\n    ext {\n        bintrayRepo = 'generic'\n        bintrayAutoPublish = true\n        mavenCentralSync = false\n    }\n\n    repositories {\n        mavenLocal()\n        mavenCentral()\n        jcenter()\n    }\n\n    group = \"org.powermock\"\n\n    apply plugin: 'java'\n    apply plugin: 'com.github.johnrengelman.shadow'\n\n    jar{\n        enabled = false\n    }\n\n    shadowJar {\n        baseName = project.name\n        version = project.version\n        classifier = \"full\"\n\n        manifest.attributes[\"Created-By\"] =\n                \"${System.getProperty(\"java.version\")} (${System.getProperty(\"java.specification.vendor\")})\"\n        manifest.attributes[\"Implementation-Title\"] = project.name + \"-full\"\n        manifest.attributes[\"Implementation-Version\"] = project.version\n\n        from(\"${rootProject.projectDir}\") {\n            include \"LICENSE.txt\"\n            into \"META-INF\"\n            expand(copyright: new Date().format(\"yyyy\"), version: project.version)\n        }\n\n        dependencies {\n            exclude(dependency {\n                !it.name.toString().contains('powermock')\n            })\n        }\n    }\n\n    apply from: \"${gradleScriptDir}/release/publish-fullJar.gradle\"\n}"
  },
  {
    "path": "gradle/release/publish-distZip.gradle",
    "content": "apply from: \"${gradleScriptDir}/publishing/publish.gradle\"\n\ntasks.bintrayUpload.mustRunAfter \"assembleDist\"\n\nbintray {\n    filesSpec{\n        from \"$buildDir/distributions\"\n        include '*.zip'\n        include '*.tar'\n        into 'distributions/'\n    }\n}\n\n\n"
  },
  {
    "path": "gradle/release/publish-fullJar.gradle",
    "content": "apply from: \"${gradleScriptDir}/publishing/publish.gradle\"\n\ntasks.bintrayUpload.mustRunAfter \"shadowJar\"\n\nbintray {\n    configurations = ['shadow']\n}\n\n"
  },
  {
    "path": "gradle/release/publish-jar.gradle",
    "content": "apply from: \"${gradleScriptDir}/publishing/publish-maven.gradle\"\n\ntasks.bintrayUpload.mustRunAfter \"build\"\n\nbintray {\n    publications = project.ext.bintrayPublications\n}"
  },
  {
    "path": "gradle/shipkit.gradle",
    "content": "shipkit {\n    gitHub.repository = \"powermock/powermock\"\n\n    gitHub.readOnlyAuthToken = \"0f1df49ac11364f542c9d3e6735ae64d010ab8e3\"\n\n    git.user = \"PowerMock Release Tools\"\n    git.email = \"<powermock.release.tools@outlook.com>\"\n    git.releasableBranchRegex = \"release/.+\"  // 'release/2.x', 'release/3.x', etc.\n\n    git.tagPrefix = \"powermock-\"\n\n    // fix for Intellj Idea, because IDE does not read env properties from ${user.home}/.profile file on MacOS\n\n    gitHub.writeAuthUser = System.getenv(\"GH_USER\") != null ? System.getenv(\"GH_USER\") : \"GH_USER-not-set-dev-mode\";\n    gitHub.writeAuthToken = System.getenv(\"GH_WRITE_TOKEN\") != null ? System.getenv(\"GH_WRITE_TOKEN\"): \"GH_WRITE_TOKEN-not-set-dev-mode\";\n\n    def buildNo = System.getenv(\"TRAVIS_BUILD_NUMBER\")\n    git.commitMessagePostfix = buildNo? \"by CI build $buildNo\\n\\n[ci skip]\" : \"by local build\\n\\n[ci skip]\"\n\n    releaseNotes.file = \"docs/release-notes/official.md\"\n    releaseNotes.labelMapping = [\n            'epic': \"Major changes\",\n            'bug': \"Bugfixes\",\n            'enhancement': \"Enhancements\",\n            'android': \"Android support\",\n            'kotlin': \"Kotlin support\",\n            'component:mockito': \"Mockito support\",\n            'component:easymock': \"EasyMock support\",\n            'component:junit': \"jUnit support\",\n            'wiki': 'Documentation',\n            'regression': 'Fix regression bug'\n    ]\n    releaseNotes.ignoreCommitsContaining = [\"[ci skip]\"]\n}\n\nboolean centralRelease = shouldReleaseToCentral(project)\n\nString versionDescription = \"PowerMock ${project.version} Final\"\nif (project.version.toString().contains(\"beta\")){\n    versionDescription = \"PowerMock ${project.version} Beta\"\n}else if (project.version.toString().contains(\"RC\")){\n    versionDescription = \"PowerMock ${project.version} Release Candidate\"\n}\n\nallprojects {\n    plugins.withId(\"org.shipkit.bintray\") {\n        bintray {\n                user = System.getenv('BINTRAY_USER')\n                key = System.getenv(\"BINTRAY_API_KEY\")\n\n                publish = true\n                override = false\n\n                pkg {\n                    userOrg = 'powermock'\n                    name = centralRelease ? \"powermock\" : \"powermock-development\"\n                    desc = project.description\n\n                    websiteUrl = 'http://powermock.org'\n                    issueTrackerUrl = 'https://powermock.com/powermock/powermock/issues'\n                    vcsUrl = 'https://github.com/powermock/powermock.git'\n\n                    licenses = ['Apache-2.0']\n                    labels = ['java', 'mock', 'mocking', 'tests']\n\n                    publicDownloadNumbers = true\n\n                    // optional version attributes\n                    version {\n\n                        name = \"powermock-${project.version}\"\n                        released  = new Date()\n                        desc = versionDescription\n                        vcsTag = \"powermock-${project.version}\"\n\n                        gpg {\n                            sign = true\n                        }\n\n                        //Automatically syncs to central repository (https://oss.sonatype.org/)\n                        mavenCentralSync {\n                            sync = centralRelease\n                            user = System.env.NEXUS_TOKEN_USER\n                            password = System.env.NEXUS_TOKEN_PWD\n                        }\n                    }\n                }\n            }\n        }\n}\n\n\n/**\n * Finds out if we should release to Maven Central.\n * To test this logic, run build with '-i' (info logging) and inspect the build output.\n */\nstatic boolean shouldReleaseToCentral(project) {\n    boolean centralReleaseByCommit = System.getenv(\"TRAVIS_COMMIT_MESSAGE\")?.contains(\"[ci maven-central-release]\")\n    boolean centralReleaseByProjectProperty = project.hasProperty(\"mavenCentralSync\") ? project.ext.mavenCentralSync : false\n\n    boolean centralRelease = (centralReleaseByCommit || centralReleaseByProjectProperty)\n    String message = \"\"\"Release was using following settings:\n - commit message contains '[ci maven-central-release]': $centralReleaseByCommit\n - project property 'mavenCentralSync' has value: $centralReleaseByProjectProperty\n - Maven Central release is enabled: $centralRelease\"\"\"\n    project.logger.info(message)\n\n    return centralRelease\n}\n"
  },
  {
    "path": "gradle/version.gradle",
    "content": "def v = Version.versionFile(project.file(\"version.properties\"))\n\nallprojects{\n    project.version = v.version\n    project.ext.versionFile = v\n}\n\nlogger.lifecycle \"Version: $project.version\"\n\nclass Version{\n    static VersionFile versionFile(file) {\n        return new VersionFile(file)\n    }\n}\n\nclass VersionFile{\n\n    private final File file\n    private version\n\n    VersionFile(file){\n        this.file = file\n    }\n\n    def getVersion() {\n        if (version == null){\n            readVersion()\n        }\n        return version\n    }\n\n    private readVersion() {\n        Properties p = new Properties()\n        FileReader reader = null\n        try {\n            reader = new FileReader(file)\n            p.load(reader)\n        } catch (Exception ignored) {\n            throw new RuntimeException(\"Cannot read version file: \" + file)\n        } finally {\n            if (reader != null){\n                reader.close()\n            }\n        }\n        version = p.getProperty(\"version\")\n    }\n}"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-4.10.2-bin.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "org.gradle.daemon=true\n//org.gradle.parallel=true"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env sh\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn () {\n    echo \"$*\"\n}\n\ndie () {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\n  NONSTOP* )\n    nonstop=true\n    ;;\nesac\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" -a \"$nonstop\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Escape application args\nsave () {\n    for i do printf %s\\\\n \"$i\" | sed \"s/'/'\\\\\\\\''/g;1s/^/'/;\\$s/\\$/' \\\\\\\\/\" ; done\n    echo \" \"\n}\nAPP_ARGS=$(save \"$@\")\n\n# Collect all arguments for the java command, following the shell quoting and substitution rules\neval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \"\\\"-Dorg.gradle.appname=$APP_BASE_NAME\\\"\" -classpath \"\\\"$CLASSPATH\\\"\" org.gradle.wrapper.GradleWrapperMain \"$APP_ARGS\"\n\n# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong\nif [ \"$(uname)\" = \"Darwin\" ] && [ \"$HOME\" = \"$PWD\" ]; then\n  cd \"$(dirname \"$0\")\"\nfi\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem  Gradle startup script for Windows\n@rem\n@rem ##########################################################################\n\n@rem Set local scope for the variables with windows NT shell\nif \"%OS%\"==\"Windows_NT\" setlocal\n\nset DIRNAME=%~dp0\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nset DEFAULT_JVM_OPTS=\n\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\n\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\nif \"%ERRORLEVEL%\" == \"0\" goto init\n\necho.\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:findJavaFromJavaHome\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n\nif exist \"%JAVA_EXE%\" goto init\n\necho.\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:init\n@rem Get command-line arguments, handling Windows variants\n\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\n\n:win9xME_args\n@rem Slurp the command line arguments.\nset CMD_LINE_ARGS=\nset _SKIP=2\n\n:win9xME_args_slurp\nif \"x%~1\" == \"x\" goto execute\n\nset CMD_LINE_ARGS=%*\n\n:execute\n@rem Setup the command line\n\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\n\n@rem Execute Gradle\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\n\n:end\n@rem End local scope for the variables with windows NT shell\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\n\n:fail\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\nrem the _cmd.exe /c_ return code!\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\nexit /b 1\n\n:mainEnd\nif \"%OS%\"==\"Windows_NT\" endlocal\n\n:omega\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/EasyMockConfiguration.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.easymock;\n\n/**\n * Configuration information about EasyMock framework and which feature is supported by version of EasyMock in runtime.\n *\n * @since 1.6.5\n */\npublic class EasyMockConfiguration {\n\n    private static final EasyMockConfiguration INSTANCE = new EasyMockConfiguration();\n    private boolean testSubjectSupported;\n    private boolean reallyEasyMock;\n    private boolean injectMocksSupported;\n\n    private EasyMockConfiguration() {\n        initTestSubjectSupported();\n        initReallyEasyMock();\n        initInjectMocksSupported();\n    }\n\n    public static EasyMockConfiguration getConfiguration() {\n        return INSTANCE;\n    }\n    \n    private void initTestSubjectSupported() {\n        try {\n            Class.forName(\"org.easymock.TestSubject\");\n            testSubjectSupported = true;\n        } catch (ClassNotFoundException e) {\n            testSubjectSupported = false;\n        }\n    }\n\n    private void initReallyEasyMock() {\n        try {\n            Class.forName(\"org.easymock.EasyMockSupport\");\n            reallyEasyMock = true;\n        } catch (ClassNotFoundException e) {\n            reallyEasyMock = false;\n        }\n    }\n\n    private void initInjectMocksSupported() {\n        try {\n            Class<?> clazz = Class.forName(\"org.easymock.EasyMockSupport\");\n            clazz.getDeclaredMethod(\"injectMocks\", Object.class);\n            injectMocksSupported = true;\n        } catch (NoSuchMethodException e) {\n            injectMocksSupported = false;\n        } catch (ClassNotFoundException e) {\n            injectMocksSupported = false;\n        }\n    }\n\n    public boolean isInjectMocksSupported() {\n        return injectMocksSupported;\n    }\n\n    public boolean isReallyEasyMock() {\n        return reallyEasyMock;\n    }\n\n    public boolean isTestSubjectSupported() {\n        return testSubjectSupported;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock;\n\nimport net.sf.cglib.proxy.Enhancer;\nimport org.easymock.ConstructorArgs;\nimport org.easymock.IExpectationSetters;\nimport org.easymock.IMocksControl;\nimport org.easymock.internal.LastControl;\nimport org.easymock.internal.MockInvocationHandler;\nimport org.easymock.internal.MocksControl;\nimport org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl;\nimport org.powermock.api.easymock.internal.invocationcontrol.NewInvocationControlAssertionError;\nimport org.powermock.api.easymock.internal.invocationcontrol.EasyMockNewInvocationControl;\nimport org.powermock.api.easymock.internal.mockstrategy.MockStrategy;\nimport org.powermock.api.easymock.internal.mockstrategy.impl.DefaultMockStrategy;\nimport org.powermock.api.easymock.internal.mockstrategy.impl.NiceMockStrategy;\nimport org.powermock.api.easymock.internal.mockstrategy.impl.StrictMockStrategy;\nimport org.powermock.api.support.SuppressCode;\nimport org.powermock.api.support.membermodification.MemberModifier;\nimport org.powermock.core.ClassReplicaCreator;\nimport org.powermock.core.DefaultFieldValueGenerator;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.core.spi.MethodInvocationControl;\nimport org.powermock.core.spi.NewInvocationControl;\nimport org.powermock.core.spi.support.InvocationSubstitute;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.lang.reflect.Proxy;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * PowerMock extends EasyMock functionality with several new features such as\n * mocking static and private methods, mocking new instances and more. Use\n * PowerMock instead of EasyMock where applicable.\n */\npublic class PowerMock extends MemberModifier {\n\n    private static final String NICE_REPLAY_AND_VERIFY_KEY = \"PowerMock.niceReplayAndVerify\";\n\n    static {\n        MockGateway.MOCK_STANDARD_METHODS = false;\n        MockGateway.MOCK_GET_CLASS_METHOD = false;\n    }\n\n    /**\n     * Creates a mock object that supports mocking of final and native methods.\n     *\n     * @param <T>     the type of the mock object\n     * @param type    the type of the mock object\n     * @param methods optionally what methods to mock\n     * @return the mock object.\n     */\n    public static synchronized <T> T createMock(Class<T> type, Method... methods) {\n        return doMock(type, false, new DefaultMockStrategy(), null, methods);\n    }\n\n    /**\n     * Creates a mock object that supports mocking of final and native methods.\n     *\n     * @param <T>  the type of the mock object\n     * @param type the type of the mock object\n     * @return the mock object.\n     */\n    public static synchronized <T> T createMock(Class<T> type) {\n        return doMock(type, false, new DefaultMockStrategy(), null, (Method[]) null);\n    }\n\n    /**\n     * Creates a mock object that supports mocking of final and native methods\n     * and invokes a specific constructor.\n     *\n     * @param <T>             the type of the mock object\n     * @param type            the type of the mock object\n     * @param constructorArgs The constructor arguments that will be used to invoke a\n     *                        special constructor.\n     * @param methods         optionally what methods to mock\n     * @return the mock object.\n     */\n    public static <T> T createMock(Class<T> type, ConstructorArgs constructorArgs, Method... methods) {\n        return doMock(type, false, new DefaultMockStrategy(), constructorArgs, methods);\n    }\n\n    /**\n     * Creates a mock object that supports mocking of final and native methods\n     * and invokes a specific constructor based on the supplied argument values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor.\n     * @return the mock object.\n     */\n    public static <T> T createMock(Class<T> type, Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMock(type, false, new DefaultMockStrategy(), constructorArgs, (Method[]) null);\n    }\n\n    /**\n     * Creates a strict mock object that supports mocking of final and native\n     * methods.\n     *\n     * @param <T>     the type of the mock object\n     * @param type    the type of the mock object\n     * @param methods optionally what methods to mock\n     * @return the mock object.\n     */\n    public static synchronized <T> T createStrictMock(Class<T> type, Method... methods) {\n        return doMock(type, false, new StrictMockStrategy(), null, methods);\n    }\n\n    /**\n     * Creates a strict mock object that supports mocking of final and native\n     * methods.\n     *\n     * @param <T>  the type of the mock object\n     * @param type the type of the mock object\n     * @return the mock object.\n     */\n    public static synchronized <T> T createStrictMock(Class<T> type) {\n        return doMock(type, false, new StrictMockStrategy(), null, (Method[]) null);\n    }\n\n    /**\n     * Creates a nice mock object that supports mocking of final and native\n     * methods.\n     *\n     * @param <T>     the type of the mock object\n     * @param type    the type of the mock object\n     * @param methods optionally what methods to mock\n     * @return the mock object.\n     */\n    public static synchronized <T> T createNiceMock(Class<T> type, Method... methods) {\n        return doMock(type, false, new NiceMockStrategy(), null, methods);\n    }\n\n    /**\n     * Creates a nice mock object that supports mocking of final and native\n     * methods.\n     *\n     * @param <T>  the type of the mock object\n     * @param type the type of the mock object\n     * @return the mock object.\n     */\n    public static synchronized <T> T createNiceMock(Class<T> type) {\n        return doMock(type, false, new NiceMockStrategy(), null, (Method[]) null);\n    }\n\n    /**\n     * Creates a strict mock object that supports mocking of final and native\n     * methods and invokes a specific constructor.\n     *\n     * @param <T>             the type of the mock object\n     * @param type            the type of the mock object\n     * @param constructorArgs The constructor arguments that will be used to invoke a\n     *                        special constructor.\n     * @param methods         optionally what methods to mock\n     * @return the mock object.\n     */\n    public static <T> T createStrictMock(Class<T> type, ConstructorArgs constructorArgs, Method... methods) {\n        return doMock(type, false, new StrictMockStrategy(), constructorArgs, methods);\n    }\n\n    /**\n     * Creates a nice mock object that supports mocking of final and native\n     * methods and invokes a specific constructor.\n     *\n     * @param <T>             the type of the mock object\n     * @param type            the type of the mock object\n     * @param constructorArgs The constructor arguments that will be used to invoke a\n     *                        special constructor.\n     * @param methods         optionally what methods to mock\n     * @return the mock object.\n     */\n    public static <T> T createNiceMock(Class<T> type, ConstructorArgs constructorArgs, Method... methods) {\n        return doMock(type, false, new NiceMockStrategy(), constructorArgs, methods);\n    }\n\n    /**\n     * Creates a strict mock object that supports mocking of final and native\n     * methods and invokes a specific constructor based on the supplied argument\n     * values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor.\n     * @return the mock object.\n     */\n    public static <T> T createStrictMock(Class<T> type, Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMock(type, false, new StrictMockStrategy(), constructorArgs, (Method[]) null);\n    }\n\n    /**\n     * Creates a nice mock object that supports mocking of final and native\n     * methods and invokes a specific constructor based on the supplied argument\n     * values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor.\n     * @return the mock object.\n     */\n    public static <T> T createNiceMock(Class<T> type, Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMock(type, false, new NiceMockStrategy(), constructorArgs, (Method[]) null);\n    }\n\n    /**\n     * Enable static mocking for a class.\n     *\n     * @param type    the class to enable static mocking\n     * @param methods optionally what methods to mock\n     */\n    public static synchronized void mockStatic(Class<?> type, Method... methods) {\n        doMock(type, true, new DefaultMockStrategy(), null, methods);\n    }\n\n    /**\n     * Enable static mocking for a class.\n     *\n     * @param type the class to enable static mocking\n     */\n    public static synchronized void mockStatic(Class<?> type) {\n        doMock(type, true, new DefaultMockStrategy(), null, (Method[]) null);\n    }\n\n    /**\n     * Enable strict static mocking for a class.\n     *\n     * @param type    the class to enable static mocking\n     * @param methods optionally what methods to mock\n     */\n    public static synchronized void mockStaticStrict(Class<?> type, Method... methods) {\n        doMock(type, true, new StrictMockStrategy(), null, methods);\n    }\n\n    /**\n     * Enable strict static mocking for a class.\n     *\n     * @param type the class to enable static mocking\n     */\n    public static synchronized void mockStaticStrict(Class<?> type) {\n        doMock(type, true, new StrictMockStrategy(), null, (Method[]) null);\n    }\n\n    /**\n     * Enable nice static mocking for a class.\n     *\n     * @param type    the class to enable static mocking\n     * @param methods optionally what methods to mock\n     */\n    public static synchronized void mockStaticNice(Class<?> type, Method... methods) {\n        doMock(type, true, new NiceMockStrategy(), null, methods);\n    }\n\n    /**\n     * Enable nice static mocking for a class.\n     *\n     * @param type the class to enable static mocking\n     */\n    public static synchronized void mockStaticNice(Class<?> type) {\n        doMock(type, true, new NiceMockStrategy(), null, (Method[]) null);\n    }\n\n    /**\n     * A utility method that may be used to specify several methods that should\n     * <i>not</i> be mocked in an easy manner (by just passing in the method\n     * names of the method you wish <i>not</i> to mock). Note that you cannot\n     * uniquely specify a method to exclude using this method if there are\n     * several methods with the same name in {@code type}. This method will\n     * mock ALL methods that doesn't match the supplied name(s) regardless of\n     * parameter types and signature. If this is not the case you should\n     * fall-back on using the {@link #createMock(Class, Method...)} method\n     * instead.\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createPartialMockForAllMethodsExcept(Class<T> type, String... methodNames) {\n        if (methodNames != null && methodNames.length == 0) {\n            return createMock(type);\n        }\n\n        return createMock(type, WhiteboxImpl.getAllMethodExcept(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to specify several methods that should\n     * <i>not</i> be nicely mocked in an easy manner (by just passing in the\n     * method names of the method you wish <i>not</i> to mock). Note that you\n     * cannot uniquely specify a method to exclude using this method if there\n     * are several methods with the same name in {@code type}. This method\n     * will mock ALL methods that doesn't match the supplied name(s) regardless\n     * of parameter types and signature. If this is not the case you should\n     * fall-back on using the {@link #createMock(Class, Method...)} method\n     * instead.\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createNicePartialMockForAllMethodsExcept(Class<T> type, String... methodNames) {\n        if (methodNames != null && methodNames.length == 0) {\n            return createNiceMock(type);\n        }\n\n        return createNiceMock(type, WhiteboxImpl.getAllMethodExcept(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to specify several methods that should\n     * <i>not</i> be strictly mocked in an easy manner (by just passing in the\n     * method names of the method you wish <i>not</i> to mock). Note that you\n     * cannot uniquely specify a method to exclude using this method if there\n     * are several methods with the same name in {@code type}. This method\n     * will mock ALL methods that doesn't match the supplied name(s) regardless\n     * of parameter types and signature. If this is not the case you should\n     * fall-back on using the {@link #createMock(Class, Method...)} method\n     * instead.\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createStrictPartialMockForAllMethodsExcept(Class<T> type, String... methodNames) {\n        if (methodNames != null && methodNames.length == 0) {\n            return createStrictMock(type);\n        }\n\n        return createStrictMock(type, WhiteboxImpl.getAllMethodExcept(type, methodNames));\n    }\n\n    /**\n     * Mock all methods of a class except for a specific one. Use this method\n     * only if you have several overloaded methods.\n     *\n     * @param <T>                 The type of the mock.\n     * @param type                The type that'll be used to create a mock instance.\n     * @param methodNameToExclude The name of the method not to mock.\n     * @param firstArgumentType   The type of the first parameter of the method not to mock\n     * @param moreTypes           Optionally more parameter types that defines the method. Note\n     *                            that this is only needed to separate overloaded methods.\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createPartialMockForAllMethodsExcept(Class<T> type, String methodNameToExclude,\n                                                                          Class<?> firstArgumentType, Class<?>... moreTypes) {\n        /*\n           * The reason why we've split the first and \"additional types\" is\n           * because it should not intervene with the mockAllExcept(type,\n           * String...methodNames) method.\n           */\n        final Class<?>[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes);\n\n        return createMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes));\n    }\n\n    /**\n     * Mock all methods of a class except for a specific one nicely. Use this\n     * method only if you have several overloaded methods.\n     *\n     * @param <T>                 The type of the mock.\n     * @param type                The type that'll be used to create a mock instance.\n     * @param methodNameToExclude The name of the method not to mock.\n     * @param firstArgumentType   The type of the first parameter of the method not to mock\n     * @param moreTypes           Optionally more parameter types that defines the method. Note\n     *                            that this is only needed to separate overloaded methods.\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createNicePartialMockForAllMethodsExcept(Class<T> type,\n                                                                              String methodNameToExclude, Class<?> firstArgumentType, Class<?>... moreTypes) {\n        /*\n           * The reason why we've split the first and \"additional types\" is\n           * because it should not intervene with the mockAllExcept(type,\n           * String...methodNames) method.\n           */\n        final Class<?>[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes);\n\n        return createNiceMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes));\n    }\n\n    /**\n     * Mock all methods of a class except for a specific one strictly. Use this\n     * method only if you have several overloaded methods.\n     *\n     * @param <T>                 The type of the mock.\n     * @param type                The type that'll be used to create a mock instance.\n     * @param methodNameToExclude The name of the method not to mock.\n     * @param firstArgumentType   The type of the first parameter of the method not to mock\n     * @param moreTypes           Optionally more parameter types that defines the method. Note\n     *                            that this is only needed to separate overloaded methods.\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createStrictPartialMockForAllMethodsExcept(Class<T> type,\n                                                                                String methodNameToExclude, Class<?> firstArgumentType, Class<?>... moreTypes) {\n        /*\n           * The reason why we've split the first and \"additional types\" is\n           * because it should not intervene with the mockAllExcept(type,\n           * String...methodNames) method.\n           */\n        final Class<?>[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes);\n\n        return createStrictMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes));\n    }\n\n    /**\n     * Mock a single specific method. Use this to handle overloaded methods.\n     *\n     * @param <T>                     The type of the mock.\n     * @param type                    The type that'll be used to create a mock instance.\n     * @param methodNameToMock        The name of the method to mock\n     * @param firstArgumentType       The type of the first parameter of the method to mock\n     * @param additionalArgumentTypes Optionally more parameter types that defines the method. Note\n     *                                that this is only needed to separate overloaded methods.\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createPartialMock(Class<T> type, String methodNameToMock,\n                                                       Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) {\n        return doMockSpecific(type, new DefaultMockStrategy(), new String[]{methodNameToMock}, null,\n                mergeArgumentTypes(firstArgumentType, additionalArgumentTypes));\n    }\n\n    /**\n     * Strictly mock a single specific method. Use this to handle overloaded\n     * methods.\n     *\n     * @param <T>                     The type of the mock.\n     * @param type                    The type that'll be used to create a mock instance.\n     * @param methodNameToMock        The name of the method to mock\n     * @param firstArgumentType       The type of the first parameter of the method to mock\n     * @param additionalArgumentTypes Optionally more parameter types that defines the method. Note\n     *                                that this is only needed to separate overloaded methods.\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createStrictPartialMock(Class<T> type, String methodNameToMock,\n                                                             Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) {\n        return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodNameToMock}, null,\n                mergeArgumentTypes(firstArgumentType, additionalArgumentTypes));\n    }\n\n    /**\n     * Nicely mock a single specific method. Use this to handle overloaded\n     * methods.\n     *\n     * @param <T>                     The type of the mock.\n     * @param type                    The type that'll be used to create a mock instance.\n     * @param methodNameToMock        The name of the method to mock\n     * @param firstArgumentType       The type of the first parameter of the method to mock\n     * @param additionalArgumentTypes Optionally more parameter types that defines the method. Note\n     *                                that this is only needed to separate overloaded methods.\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createNicePartialMock(Class<T> type, String methodNameToMock,\n                                                           Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) {\n        return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodNameToMock}, null,\n                mergeArgumentTypes(firstArgumentType, additionalArgumentTypes));\n    }\n\n    /**\n     * Mock a single static method.\n     *\n     * @param clazz                   The class where the method is specified in.\n     * @param methodNameToMock        The first argument\n     * @param firstArgumentType       The first argument type.\n     * @param additionalArgumentTypes Optional additional argument types.\n     */\n    public static synchronized void mockStaticPartial(Class<?> clazz, String methodNameToMock,\n                                                      Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) {\n        doMockSpecific(clazz, new DefaultMockStrategy(), new String[]{methodNameToMock}, null,\n                mergeArgumentTypes(firstArgumentType, additionalArgumentTypes));\n    }\n\n    /**\n     * Mock a single static method (strict).\n     *\n     * @param clazz                   The class where the method is specified in.\n     * @param methodNameToMock        The first argument\n     * @param firstArgumentType       The first argument type.\n     * @param additionalArgumentTypes Optional additional argument types.\n     */\n    public static synchronized void mockStaticPartialStrict(Class<?> clazz, String methodNameToMock,\n                                                            Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) {\n        doMockSpecific(clazz, new StrictMockStrategy(), new String[]{methodNameToMock}, null,\n                mergeArgumentTypes(firstArgumentType, additionalArgumentTypes));\n    }\n\n    /**\n     * Mock a single static method (nice).\n     *\n     * @param clazz                   The class where the method is specified in.\n     * @param methodNameToMock        The first argument\n     * @param firstArgumentType       The first argument type.\n     * @param additionalArgumentTypes Optional additional argument types.\n     */\n    public static synchronized void mockStaticPartialNice(Class<?> clazz, String methodNameToMock,\n                                                          Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) {\n        doMockSpecific(clazz, new NiceMockStrategy(), new String[]{methodNameToMock}, null,\n                mergeArgumentTypes(firstArgumentType, additionalArgumentTypes));\n    }\n\n    /**\n     * A utility method that may be used to mock several <b>static</b> methods\n     * in an easy way (by just passing in the method names of the method you\n     * wish to mock). Note that you cannot uniquely specify a method to mock\n     * using this method if there are several methods with the same name in\n     * {@code type}. This method will mock ALL methods that match the\n     * supplied name regardless of parameter types and signature. If this is the\n     * case you should fall-back on using the\n     * {@link #mockStatic(Class, Method...)} method instead.\n     *\n     * @param clazz       The class that contains the static methods that should be\n     *                    mocked.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #mockStatic(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     */\n    public static synchronized void mockStaticPartial(Class<?> clazz, String... methodNames) {\n        mockStatic(clazz, Whitebox.getMethods(clazz, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to mock several <b>static</b> methods\n     * (strict) in an easy way (by just passing in the method names of the\n     * method you wish to mock). Note that you cannot uniquely specify a method\n     * to mock using this method if there are several methods with the same name\n     * in {@code type}. This method will mock ALL methods that match the\n     * supplied name regardless of parameter types and signature. If this is the\n     * case you should fall-back on using the\n     * {@link #mockStaticStrict(Class, Method...)} method instead.\n     *\n     * @param clazz       The class that contains the static methods that should be\n     *                    mocked.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #mockStatic(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     */\n    public static synchronized void mockStaticPartialStrict(Class<?> clazz, String... methodNames) {\n        mockStaticStrict(clazz, Whitebox.getMethods(clazz, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to mock several <b>static</b> methods\n     * (nice) in an easy way (by just passing in the method names of the method\n     * you wish to mock). Note that you cannot uniquely specify a method to mock\n     * using this method if there are several methods with the same name in\n     * {@code type}. This method will mock ALL methods that match the\n     * supplied name regardless of parameter types and signature. If this is the\n     * case you should fall-back on using the\n     * {@link #mockStaticStrict(Class, Method...)} method instead.\n     *\n     * @param clazz       The class that contains the static methods that should be\n     *                    mocked.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #mockStatic(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     */\n    public static synchronized void mockStaticPartialNice(Class<?> clazz, String... methodNames) {\n        mockStaticNice(clazz, Whitebox.getMethods(clazz, methodNames));\n    }\n\n    static <T> T doMockSpecific(Class<T> type, MockStrategy mockStrategy, String[] methodNamesToMock,\n                                ConstructorArgs constructorArgs, Class<?>... argumentTypes) {\n        List<Method> methods = new LinkedList<Method>();\n        for (String methodName : methodNamesToMock) {\n            methods.add(WhiteboxImpl.findMethodOrThrowException(type, methodName, argumentTypes));\n        }\n\n        final Method[] methodArray = methods.toArray(new Method[0]);\n        if (WhiteboxImpl.areAllMethodsStatic(methodArray)) {\n            if (mockStrategy instanceof DefaultMockStrategy) {\n                mockStatic(type, methodArray);\n            } else if (mockStrategy instanceof StrictMockStrategy) {\n                mockStaticStrict(type, methodArray);\n            } else {\n                mockStaticNice(type, methodArray);\n            }\n            return null;\n        }\n\n        T mock = null;\n        if (mockStrategy instanceof DefaultMockStrategy) {\n            mock = createMock(type, constructorArgs, methodArray);\n        } else if (mockStrategy instanceof StrictMockStrategy) {\n            mock = createStrictMock(type, constructorArgs, methodArray);\n        } else {\n            mock = createNiceMock(type, constructorArgs, methodArray);\n        }\n\n        return mock;\n    }\n\n    /**\n     * A utility method that may be used to mock several methods in an easy way\n     * (by just passing in the method names of the method you wish to mock).\n     * Note that you cannot uniquely specify a method to mock using this method\n     * if there are several methods with the same name in {@code type}.\n     * This method will mock ALL methods that match the supplied name regardless\n     * of parameter types and signature. If this is the case you should\n     * fall-back on using the {@link #createMock(Class, Method...)} method\n     * instead.\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createPartialMock(Class<T> type, String... methodNames) {\n        return createMock(type, Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to mock several methods in an easy way\n     * (by just passing in the method names of the method you wish to mock).\n     * Note that you cannot uniquely specify a method to mock using this method\n     * if there are several methods with the same name in {@code type}.\n     * This method will mock ALL methods that match the supplied name regardless\n     * of parameter types and signature. If this is the case you should\n     * fall-back on using the {@link #createMock(Class, Method...)} method\n     * instead.\n     * <p/>\n     * With this method you can specify where the class hierarchy the methods\n     * are located. This is useful in, for example, situations where class A\n     * extends B and both have a method called \"mockMe\" (A overrides B's mockMe\n     * method) and you like to specify the only the \"mockMe\" method in B should\n     * be mocked. \"mockMe\" in A should be left intact. In this case you should\n     * do:\n     * <p/>\n     * <pre>\n     * A tested = createPartialMock(A.class, B.class, &quot;mockMe&quot;);\n     * </pre>\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param where       Where in the class hierarchy the methods resides.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createPartialMock(Class<T> type, Class<? super T> where, String... methodNames) {\n        return createMock(type, Whitebox.getMethods(where, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to strictly mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Note that you cannot uniquely specify a method to mock using this\n     * method if there are several methods with the same name in\n     * {@code type}. This method will mock ALL methods that match the\n     * supplied name regardless of parameter types and signature. If this is the\n     * case you should fall-back on using the\n     * {@link #createMock(Class, Method...)} method instead.\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createStrictPartialMock(Class<T> type, String... methodNames) {\n        return createStrictMock(type, Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to strictly mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Note that you cannot uniquely specify a method to mock using this\n     * method if there are several methods with the same name in\n     * {@code type}. This method will mock ALL methods that match the\n     * supplied name regardless of parameter types and signature. If this is the\n     * case you should fall-back on using the\n     * {@link #createMock(Class, Method...)} method instead.\n     * <p/>\n     * With this method you can specify where the class hierarchy the methods\n     * are located. This is useful in, for example, situations where class A\n     * extends B and both have a method called \"mockMe\" (A overrides B's mockMe\n     * method) and you like to specify the only the \"mockMe\" method in B should\n     * be mocked. \"mockMe\" in A should be left intact. In this case you should\n     * do:\n     * <p/>\n     * <pre>\n     * A tested = createPartialMockStrict(A.class, B.class, &quot;mockMe&quot;);\n     * </pre>\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param where       Where in the class hierarchy the methods resides.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createStrictPartialMock(Class<T> type, Class<? super T> where,\n                                                             String... methodNames) {\n        return createStrictMock(type, Whitebox.getMethods(where, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to nicely mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Note that you cannot uniquely specify a method to mock using this\n     * method if there are several methods with the same name in\n     * {@code type}. This method will mock ALL methods that match the\n     * supplied name regardless of parameter types and signature. If this is the\n     * case you should fall-back on using the\n     * {@link #createMock(Class, Method...)} method instead.\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createNicePartialMock(Class<T> type, String... methodNames) {\n        return createNiceMock(type, Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to nicely mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Note that you cannot uniquely specify a method to mock using this\n     * method if there are several methods with the same name in\n     * {@code type}. This method will mock ALL methods that match the\n     * supplied name regardless of parameter types and signature. If this is the\n     * case you should fall-back on using the\n     * {@link #createMock(Class, Method...)} method instead.\n     * <p/>\n     * With this method you can specify where the class hierarchy the methods\n     * are located. This is useful in, for example, situations where class A\n     * extends B and both have a method called \"mockMe\" (A overrides B's mockMe\n     * method) and you like to specify the only the \"mockMe\" method in B should\n     * be mocked. \"mockMe\" in A should be left intact. In this case you should\n     * do:\n     * <p/>\n     * <pre>\n     * A tested = createPartialMockNice(A.class, B.class, &quot;mockMe&quot;);\n     * </pre>\n     *\n     * @param <T>         The type of the mock.\n     * @param type        The type that'll be used to create a mock instance.\n     * @param where       Where in the class hierarchy the methods resides.\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return A mock object of type <T>.\n     */\n    public static synchronized <T> T createNicePartialMock(Class<T> type, Class<? super T> where, String... methodNames) {\n        return createNiceMock(type, Whitebox.getMethods(where, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to mock several methods in an easy way\n     * (by just passing in the method names of the method you wish to mock). The\n     * mock object created will support mocking of final methods and invokes the\n     * default constructor (even if it's private).\n     *\n     * @param <T>         the type of the mock object\n     * @param type        the type of the mock object\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return the mock object.\n     */\n    public static <T> T createPartialMockAndInvokeDefaultConstructor(Class<T> type, String... methodNames)\n            throws Exception {\n        return createMock(type, new ConstructorArgs(Whitebox.getConstructor(type)),\n                Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to nicely mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). The mock object created will support mocking of final methods and\n     * invokes the default constructor (even if it's private).\n     *\n     * @param <T>         the type of the mock object\n     * @param type        the type of the mock object\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return the mock object.\n     */\n    public static <T> T createNicePartialMockAndInvokeDefaultConstructor(Class<T> type, String... methodNames)\n            throws Exception {\n        return createNiceMock(type, new ConstructorArgs(Whitebox.getConstructor(type)),\n                Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to strictly mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). The mock object created will support mocking of final methods and\n     * invokes the default constructor (even if it's private).\n     *\n     * @param <T>         the type of the mock object\n     * @param type        the type of the mock object\n     * @param methodNames The names of the methods that should be mocked. If\n     *                    {@code null}, then this method will have the same effect\n     *                    as just calling {@link #createMock(Class, Method...)} with the\n     *                    second parameter as {@code new Method[0]} (i.e. all\n     *                    methods in that class will be mocked).\n     * @return the mock object.\n     */\n    public static <T> T createStrictPartialMockAndInvokeDefaultConstructor(Class<T> type, String... methodNames)\n            throws Exception {\n        return createStrictMock(type, new ConstructorArgs(Whitebox.getConstructor(type)),\n                Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to mock several methods in an easy way\n     * (by just passing in the method names of the method you wish to mock). The\n     * mock object created will support mocking of final and native methods and\n     * invokes a specific constructor based on the supplied argument values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param methodNames          The names of the methods that should be mocked. If\n     *                             {@code null}, then this method will have the same effect\n     *                             as just calling {@link #createMock(Class, Method...)} with the\n     *                             second parameter as {@code new Method[0]} (i.e. all\n     *                             methods in that class will be mocked).\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor. (optional)\n     * @return the mock object.\n     */\n    public static <T> T createPartialMock(Class<T> type, String[] methodNames, Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMock(type, false, new DefaultMockStrategy(), constructorArgs, Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * * A utility method that may be used to strictly mock several methods in\n     * an easy way (by just passing in the method names of the method you wish\n     * to mock). The mock object created will support mocking of final and\n     * native methods and invokes a specific constructor based on the supplied\n     * argument values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param methodNames          The names of the methods that should be mocked. If\n     *                             {@code null}, then this method will have the same effect\n     *                             as just calling {@link #createMock(Class, Method...)} with the\n     *                             second parameter as {@code new Method[0]} (i.e. all\n     *                             methods in that class will be mocked).\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor. (optional)\n     * @return the mock object.\n     */\n    public static <T> T createStrictPartialMock(Class<T> type, String[] methodNames, Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMock(type, false, new StrictMockStrategy(), constructorArgs, Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * * A utility method that may be used to nicely mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). The mock object created will support mocking of final and native\n     * methods and invokes a specific constructor based on the supplied argument\n     * values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param methodNames          The names of the methods that should be mocked. If\n     *                             {@code null}, then this method will have the same effect\n     *                             as just calling {@link #createMock(Class, Method...)} with the\n     *                             second parameter as {@code new Method[0]} (i.e. all\n     *                             methods in that class will be mocked).\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor. (optional)\n     * @return the mock object.\n     */\n    public static <T> T createNicePartialMock(Class<T> type, String[] methodNames, Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMock(type, false, new NiceMockStrategy(), constructorArgs, Whitebox.getMethods(type, methodNames));\n    }\n\n    /**\n     * A utility method that may be used to mock several methods in an easy way\n     * (by just passing in the method names of the method you wish to mock). Use\n     * this to handle overloaded methods. The mock object created will support\n     * mocking of final and native methods and invokes a specific constructor\n     * based on the supplied argument values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param methodName           The names of the methods that should be mocked. If\n     *                             {@code null}, then this method will have the same effect\n     *                             as just calling {@link #createMock(Class, Method...)} with the\n     *                             second parameter as {@code new Method[0]} (i.e. all\n     *                             methods in that class will be mocked).\n     * @param methodParameterTypes Parameter types that defines the method. Note that this is\n     *                             only needed to separate overloaded methods.\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor. (optional)\n     * @return the mock object.\n     */\n    public static <T> T createPartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes,\n                                          Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMockSpecific(type, new DefaultMockStrategy(), new String[]{methodName}, constructorArgs,\n                methodParameterTypes);\n    }\n\n    /**\n     * A utility method that may be used to strictly mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Use this to handle overloaded methods. The mock object created\n     * will support mocking of final and native methods and invokes a specific\n     * constructor based on the supplied argument values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param methodName           The names of the methods that should be mocked. If\n     *                             {@code null}, then this method will have the same effect\n     *                             as just calling {@link #createMock(Class, Method...)} with the\n     *                             second parameter as {@code new Method[0]} (i.e. all\n     *                             methods in that class will be mocked).\n     * @param methodParameterTypes Parameter types that defines the method. Note that this is\n     *                             only needed to separate overloaded methods.\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor. (optional)\n     * @return the mock object.\n     */\n    public static <T> T createStrictPartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes,\n                                                Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodName}, constructorArgs,\n                methodParameterTypes);\n    }\n\n    /**\n     * A utility method that may be used to nicely mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Use this to handle overloaded methods. The mock object created\n     * will support mocking of final and native methods and invokes a specific\n     * constructor based on the supplied argument values.\n     *\n     * @param <T>                  the type of the mock object\n     * @param type                 the type of the mock object\n     * @param methodName           The names of the methods that should be mocked. If\n     *                             {@code null}, then this method will have the same effect\n     *                             as just calling {@link #createMock(Class, Method...)} with the\n     *                             second parameter as {@code new Method[0]} (i.e. all\n     *                             methods in that class will be mocked).\n     * @param methodParameterTypes Parameter types that defines the method. Note that this is\n     *                             only needed to separate overloaded methods.\n     * @param constructorArguments The constructor arguments that will be used to invoke a\n     *                             certain constructor. (optional)\n     * @return the mock object.\n     */\n    public static <T> T createNicePartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes,\n                                              Object... constructorArguments) {\n        Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments);\n        ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments);\n        return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs,\n                methodParameterTypes);\n    }\n\n    /**\n     * A utility method that may be used to mock several methods in an easy way\n     * (by just passing in the method names of the method you wish to mock). Use\n     * this to handle overloaded methods <i>and</i> overloaded constructors. The\n     * mock object created will support mocking of final and native methods and\n     * invokes a specific constructor based on the supplied argument values.\n     *\n     * @param <T>                       the type of the mock object\n     * @param type                      the type of the mock object\n     * @param methodName                The names of the methods that should be mocked. If\n     *                                  {@code null}, then this method will have the same effect\n     *                                  as just calling {@link #createMock(Class, Method...)} with the\n     *                                  second parameter as {@code new Method[0]} (i.e. all\n     *                                  methods in that class will be mocked).\n     * @param methodParameterTypes      Parameter types that defines the method. Note that this is\n     *                                  only needed to separate overloaded methods.\n     * @param constructorArguments      The constructor arguments that will be used to invoke a\n     *                                  certain constructor.\n     * @param constructorParameterTypes Parameter types that defines the constructor that should be\n     *                                  invoked. Note that this is only needed to separate overloaded\n     *                                  constructors.\n     * @return the mock object.\n     */\n    public static <T> T createPartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes,\n                                          Object[] constructorArguments, Class<?>[] constructorParameterTypes) {\n        ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes),\n                constructorArguments);\n        return doMockSpecific(type, new DefaultMockStrategy(), new String[]{methodName}, constructorArgs,\n                methodParameterTypes);\n    }\n\n    /**\n     * A utility method that may be used to strictly mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Use this to handle overloaded methods <i>and</i> overloaded\n     * constructors. The mock object created will support mocking of final and\n     * native methods and invokes a specific constructor based on the supplied\n     * argument values.\n     *\n     * @param <T>                       the type of the mock object\n     * @param type                      the type of the mock object\n     * @param methodName                The names of the methods that should be mocked. If\n     *                                  {@code null}, then this method will have the same effect\n     *                                  as just calling {@link #createMock(Class, Method...)} with the\n     *                                  second parameter as {@code new Method[0]} (i.e. all\n     *                                  methods in that class will be mocked).\n     * @param methodParameterTypes      Parameter types that defines the method. Note that this is\n     *                                  only needed to separate overloaded methods.\n     * @param constructorArguments      The constructor arguments that will be used to invoke a\n     *                                  certain constructor.\n     * @param constructorParameterTypes Parameter types that defines the constructor that should be\n     *                                  invoked. Note that this is only needed to separate overloaded\n     *                                  constructors.\n     * @return the mock object.\n     */\n    public static <T> T createStrictPartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes,\n                                                Object[] constructorArguments, Class<?>[] constructorParameterTypes) {\n        ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes),\n                constructorArguments);\n        return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodName}, constructorArgs,\n                methodParameterTypes);\n    }\n\n    /**\n     * A utility method that may be used to nicely mock several methods in an\n     * easy way (by just passing in the method names of the method you wish to\n     * mock). Use this to handle overloaded methods <i>and</i> overloaded\n     * constructors. The mock object created will support mocking of final and\n     * native methods and invokes a specific constructor based on the supplied\n     * argument values.\n     *\n     * @param <T>                       the type of the mock object\n     * @param type                      the type of the mock object\n     * @param methodName                The names of the methods that should be mocked. If\n     *                                  {@code null}, then this method will have the same effect\n     *                                  as just calling {@link #createMock(Class, Method...)} with the\n     *                                  second parameter as {@code new Method[0]} (i.e. all\n     *                                  methods in that class will be mocked).\n     * @param methodParameterTypes      Parameter types that defines the method. Note that this is\n     *                                  only needed to separate overloaded methods.\n     * @param constructorArguments      The constructor arguments that will be used to invoke a\n     *                                  certain constructor.\n     * @param constructorParameterTypes Parameter types that defines the constructor that should be\n     *                                  invoked. Note that this is only needed to separate overloaded\n     *                                  constructors.\n     * @return the mock object.\n     */\n    public static <T> T createNicePartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes,\n                                              Object[] constructorArguments, Class<?>[] constructorParameterTypes) {\n        ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes),\n                constructorArguments);\n        return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs,\n                methodParameterTypes);\n    }\n\n    /**\n     * Used to specify expectations on private static methods. If possible use\n     * variant with only method name.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectPrivate(Class<?> clazz, Method method,\n                                                                        Object... arguments) throws Exception {\n        return doExpectPrivate(clazz, method, arguments);\n    }\n\n    /**\n     * Used to specify expectations on private methods. If possible use variant\n     * with only method name.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectPrivate(Object instance, Method method,\n                                                                        Object... arguments) throws Exception {\n        return doExpectPrivate(instance, method, arguments);\n    }\n\n    /**\n     * Used to specify expectations on private methods. Use this method to\n     * handle overloaded methods.\n     */\n    @SuppressWarnings(\"all\")\n    public static synchronized <T> IExpectationSetters<T> expectPrivate(Object instance, String methodName,\n                                                                        Class<?>[] parameterTypes, Object... arguments) throws Exception {\n\n        if (arguments == null) {\n            arguments = new Object[0];\n        }\n\n        if (instance == null) {\n            throw new IllegalArgumentException(\"instance cannot be null.\");\n        } else if (arguments.length != parameterTypes.length) {\n            throw new IllegalArgumentException(\n                    \"The length of the arguments must be equal to the number of parameter types.\");\n        }\n\n        Method foundMethod = Whitebox.getMethod(instance.getClass(), methodName, parameterTypes);\n\n        WhiteboxImpl.throwExceptionIfMethodWasNotFound(instance.getClass(), methodName, foundMethod, parameterTypes);\n\n        return doExpectPrivate(instance, foundMethod, arguments);\n    }\n\n    /**\n     * Used to specify expectations on methods using the method name. Works on\n     * for example private or package private methods.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectPrivate(Object instance, String methodName,\n                                                                        Object... arguments) throws Exception {\n        if (instance == null) {\n            throw new IllegalArgumentException(\"Instance or class cannot be null.\");\n        }\n\n        return expectPrivate(instance, methodName, Whitebox.getType(instance), arguments);\n    }\n\n    /**\n     * Used to specify expectations on methods without specifying a method name.\n     * Works on for example private or package private methods. PowerMock tries\n     * to find a unique method to expect based on the argument parameters. If\n     * PowerMock is unable to locate a unique method you need to revert to using\n     * {@link #expectPrivate(Object, String, Object...)}.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectPrivate(Object instance, Object... arguments)\n            throws Exception {\n        return expectPrivate(instance, null, Whitebox.getType(instance), arguments);\n    }\n\n    /**\n     * Used to specify expectations on methods using the method name at a\n     * specific place in the class hierarchy (specified by the\n     * {@code where} parameter). Works on for example private or package\n     * private methods.\n     * <p/>\n     * Use this for overloaded methods.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectPrivate(Object instance, String methodName,\n                                                                        Class<?> where, Class<?>[] parameterTypes, Object... arguments) throws Exception {\n        if (instance == null) {\n            throw new IllegalArgumentException(\"Instance or class to expect cannot be null.\");\n        }\n        Method[] methods = null;\n        if (methodName != null) {\n            if (parameterTypes == null) {\n                methods = Whitebox.getMethods(where, methodName);\n            } else {\n                methods = new Method[]{Whitebox.getMethod(where, methodName, parameterTypes)};\n            }\n        }\n        Method methodToExpect;\n        if (methods != null && methods.length == 1) {\n            methodToExpect = methods[0];\n        } else {\n            methodToExpect = WhiteboxImpl.findMethodOrThrowException(instance, null, methodName, arguments);\n        }\n\n        return doExpectPrivate(instance, methodToExpect, arguments);\n    }\n\n    /**\n     * Used to specify expectations on methods using the method name at a\n     * specific place in the class hierarchy (specified by the\n     * {@code where} parameter). Works on for example private or package\n     * private methods.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectPrivate(Object instance, String methodName,\n                                                                        Class<?> where, Object... arguments) throws Exception {\n        return expectPrivate(instance, methodName, where, null, arguments);\n    }\n\n    /**\n     * This method just delegates to EasyMock class extensions\n     * {@link org.easymock.EasyMock#expectLastCall()} method.\n     *\n     * @return The expectation setter.\n     * @see org.easymock.EasyMock#expectLastCall()\n     */\n    public static synchronized IExpectationSetters<Object> expectLastCall() {\n        return org.easymock.EasyMock.expectLastCall();\n    }\n\n    /**\n     * Sometimes it is useful to allow replay and verify on non-mocks. For\n     * example when using partial mocking in some tests and no mocking in other\n     * test-methods, but using the same setUp and tearDown.\n     */\n    public static synchronized void niceReplayAndVerify() {\n        MockRepository.putAdditionalState(NICE_REPLAY_AND_VERIFY_KEY, true);\n    }\n\n    /**\n     * Test if a object is a mock created by EasyMock or not.\n     */\n    private static boolean isEasyMocked(Object mock) {\n        return Enhancer.isEnhanced(mock.getClass()) || Proxy.isProxyClass(mock.getClass());\n    }\n\n    /**\n     * Replay all classes and mock objects known by PowerMock. This includes all\n     * classes that are prepared for test using the {@link PrepareForTest} or\n     * {@link PrepareOnlyThisForTest} annotations and all classes that have had\n     * their static initializers removed by using the\n     * {@link SuppressStaticInitializationFor} annotation. It also includes all\n     * mock instances created by PowerMock such as those created or used by\n     * {@link #createMock(Class, Method...)},\n     * {@link #mockStatic(Class, Method...)},\n     * {@link #expectNew(Class, Object...)},\n     * {@link #createPartialMock(Class, String...)} etc.\n     * <p/>\n     * To make it easy to pass in additional mocks <i>not</i> created by the\n     * PowerMock API you can optionally specify them as <tt>additionalMocks</tt>\n     * . These are typically those mock objects you have created using pure\n     * EasyMock or EasyMock class extensions. No additional mocks needs to be\n     * specified if you're only using PowerMock API methods.\n     * <p/>\n     * Note that the <tt>additionalMocks</tt> are also automatically verified\n     * when invoking the {@link #verifyAll()} method.\n     *\n     * @param additionalMocks Mocks not created by the PowerMock API. These are typically\n     *                        those mock objects you have created using pure EasyMock or\n     *                        EasyMock class extensions.\n     */\n    public static synchronized void replayAll(Object... additionalMocks) {\n        MockRepository.addObjectsToAutomaticallyReplayAndVerify(additionalMocks);\n\n        for (Object classToReplayOrVerify : MockRepository.getObjectsToAutomaticallyReplayAndVerify()) {\n            replay(classToReplayOrVerify);\n        }\n    }\n\n    /**\n     * Reset all classes and mock objects known by PowerMock. This includes all\n     * classes that are prepared for test using the {@link PrepareForTest} or\n     * {@link PrepareOnlyThisForTest} annotations and all classes that have had\n     * their static initializers removed by using the\n     * {@link SuppressStaticInitializationFor} annotation. It also includes all\n     * mock instances created by PowerMock such as those created or used by\n     * {@link #createMock(Class, Method...)},\n     * {@link #mockStatic(Class, Method...)},\n     * {@link #expectNew(Class, Object...)},\n     * {@link #createPartialMock(Class, String...)} etc.\n     * <p/>\n     * To make it easy to pass in additional mocks <i>not</i> created by the\n     * PowerMock API you can optionally specify them as <tt>additionalMocks</tt>\n     * . These are typically those mock objects you have created using pure\n     * EasyMock or EasyMock class extensions. No additional mocks needs to be\n     * specified if you're only using PowerMock API methods.\n     *\n     * @param additionalMocks Mocks not created by the PowerMock API. These are typically\n     *                        those mock objects you have created using pure EasyMock or\n     *                        EasyMock class extensions.\n     */\n    public static synchronized void resetAll(Object... additionalMocks) {\n        MockRepository.addObjectsToAutomaticallyReplayAndVerify(additionalMocks);\n\n        for (Object classToReplayOrVerify : MockRepository.getObjectsToAutomaticallyReplayAndVerify()) {\n            reset(classToReplayOrVerify);\n        }\n    }\n\n    /**\n     * Reset a list of class mocks.\n     */\n    public static synchronized void reset(Class<?>... classMocks) {\n        for (Class<?> type : classMocks) {\n            final MethodInvocationControl invocationHandler = MockRepository.getStaticMethodInvocationControl(type);\n            if (invocationHandler != null) {\n                invocationHandler.reset();\n            }\n            NewInvocationControl<?> newInvocationControl = MockRepository.getNewInstanceControl(type);\n            if (newInvocationControl != null) {\n                try {\n                    newInvocationControl.reset();\n                } catch (AssertionError e) {\n                    NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type);\n                }\n            }\n        }\n    }\n\n    /**\n     * Reset a list of mock objects or classes.\n     */\n    public static synchronized void reset(Object... mocks) {\n        try {\n            for (Object mock : mocks) {\n                if (mock instanceof Class<?>) {\n                    reset((Class<?>) mock);\n                } else {\n                    MethodInvocationControl invocationControl = MockRepository.getInstanceMethodInvocationControl(mock);\n                    if (invocationControl != null) {\n                        invocationControl.reset();\n                    } else {\n                        if (isNiceReplayAndVerifyMode() && !isEasyMocked(mock)) {\n                            // ignore non-mock\n                        } else {\n                            /*\n                                    * Delegate to easy mock class extension if we have\n                                    * no handler registered for this object.\n                                    */\n                            try {\n                                org.easymock.EasyMock.reset(mock);\n                            } catch (RuntimeException e) {\n                                throw new RuntimeException(mock + \" is not a mock object\", e);\n                            }\n                        }\n                    }\n                }\n            }\n        } catch (Throwable t) {\n            MockRepository.putAdditionalState(NICE_REPLAY_AND_VERIFY_KEY, false);\n            if (t instanceof RuntimeException) {\n                throw (RuntimeException) t;\n            } else if (t instanceof Error) {\n                throw (Error) t;\n            }\n            throw new RuntimeException(t);\n        }\n    }\n\n    /**\n     * Verify all classes and mock objects known by PowerMock. This includes all\n     * classes that are prepared for test using the {@link PrepareForTest} or\n     * {@link PrepareOnlyThisForTest} annotations and all classes that have had\n     * their static initializers removed by using the\n     * {@link SuppressStaticInitializationFor} annotation. It also includes all\n     * mock instances created by PowerMock such as those created or used by\n     * {@link #createMock(Class, Method...)},\n     * {@link #mockStatic(Class, Method...)},\n     * {@link #expectNew(Class, Object...)},\n     * {@link #createPartialMock(Class, String...)} etc.\n     * <p/>\n     * Note that all <tt>additionalMocks</tt> passed to the\n     * {@link #replayAll(Object...)} method are also verified here\n     * automatically.\n     */\n    public static synchronized void verifyAll() {\n        for (Object classToReplayOrVerify : MockRepository.getObjectsToAutomaticallyReplayAndVerify()) {\n            verify(classToReplayOrVerify);\n        }\n    }\n\n    /**\n     * Switches the mocks or classes to replay mode. Note that you must use this\n     * method when using PowerMock!\n     *\n     * @param mocks mock objects or classes loaded by PowerMock.\n     * @throws RuntimeException If something unexpected goes wrong.\n     */\n    public static synchronized void replay(Object... mocks) {\n        try {\n            for (Object mock : mocks) {\n                if (mock instanceof Class<?>) {\n                    replay((Class<?>) mock);\n                } else {\n                    MethodInvocationControl invocationControl = MockRepository.getInstanceMethodInvocationControl(mock);\n                    if (invocationControl != null) {\n                        invocationControl.replay();\n                    } else {\n                        if (isNiceReplayAndVerifyMode() && !isEasyMocked(mock)) {\n                            // ignore non-mock\n                        } else {\n                            /*\n                                    * Delegate to easy mock class extension if we have\n                                    * no handler registered for this object.\n                                    */\n                            try {\n                                org.easymock.EasyMock.replay(mock);\n                            } catch (RuntimeException e) {\n                                throw new RuntimeException(mock + \" is not a mock object\", e);\n                            }\n                        }\n                    }\n                }\n            }\n        } catch (Throwable t) {\n            MockRepository.putAdditionalState(NICE_REPLAY_AND_VERIFY_KEY, false);\n            if (t instanceof RuntimeException) {\n                throw (RuntimeException) t;\n            } else if (t instanceof Error) {\n                throw (Error) t;\n            }\n            throw new RuntimeException(t);\n        }\n    }\n\n    /**\n     * Switches the mocks or classes to verify mode. Note that you must use this\n     * method when using PowerMock!\n     *\n     * @param objects mock objects or classes loaded by PowerMock.\n     */\n    public static synchronized void verify(Object... objects) {\n        for (Object mock : objects) {\n            if (mock instanceof Class<?>) {\n                verifyClass((Class<?>) mock);\n            } else {\n                EasyMockMethodInvocationControl invocationControl = (EasyMockMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(mock);\n                if (invocationControl != null) {\n                    invocationControl.verify();\n                } else {\n                    if (isNiceReplayAndVerifyMode() && !isEasyMocked(mock)) {\n                        // ignore non-mock\n                    } else {\n                        /*\n                               * Delegate to easy mock class extension if we have no\n                               * handler registered for this object.\n                               */\n                        try {\n                            org.easymock.EasyMock.verify(mock);\n                        } catch (RuntimeException e) {\n                            throw new RuntimeException(mock + \" is not a mock object\", e);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Convenience method for createMock followed by expectNew.\n     *\n     * @param type      The class that should be mocked.\n     * @param arguments The constructor arguments.\n     * @return A mock object of the same type as the mock.\n     * @throws Exception\n     */\n    public static synchronized <T> T createMockAndExpectNew(Class<T> type, Object... arguments) throws Exception {\n        T mock = createMock(type);\n        expectNew(type, arguments).andReturn(mock);\n        return mock;\n    }\n\n    /**\n     * Convenience method for createMock followed by expectNew when PowerMock\n     * cannot determine which constructor to use automatically. This happens\n     * when you have one constructor taking a primitive type and another one\n     * taking the wrapper type of the primitive. For example {@code int}\n     * and {@code Integer}.\n     *\n     * @param type           The class that should be mocked.\n     * @param parameterTypes The constructor parameter types.\n     * @param arguments      The constructor arguments.\n     * @return A mock object of the same type as the mock.\n     * @throws Exception\n     */\n    public static synchronized <T> T createMockAndExpectNew(Class<T> type, Class<?>[] parameterTypes,\n                                                            Object... arguments) throws Exception {\n        T mock = createMock(type);\n        expectNew(type, parameterTypes, arguments).andReturn(mock);\n        return mock;\n    }\n\n    /**\n     * Convenience method for createNiceMock followed by expectNew.\n     *\n     * @param type      The class that should be mocked.\n     * @param arguments The constructor arguments.\n     * @return A mock object of the same type as the mock.\n     * @throws Exception\n     */\n    public static synchronized <T> T createNiceMockAndExpectNew(Class<T> type, Object... arguments) throws Exception {\n        T mock = createNiceMock(type);\n        IExpectationSetters<T> expectationSetters = expectNiceNew(type, arguments);\n        if (expectationSetters != null) {\n            expectationSetters.andReturn(mock);\n        }\n        return mock;\n    }\n\n    /**\n     * Convenience method for createNiceMock followed by expectNew when\n     * PowerMock cannot determine which constructor to use automatically. This\n     * happens when you have one constructor taking a primitive type and another\n     * one taking the wrapper type of the primitive. For example\n     * {@code int} and {@code Integer}.\n     *\n     * @param type           The class that should be mocked.\n     * @param parameterTypes The constructor parameter types.\n     * @param arguments      The constructor arguments.\n     * @return A mock object of the same type as the mock.\n     * @throws Exception\n     */\n    public static synchronized <T> T createNiceMockAndExpectNew(Class<T> type, Class<?>[] parameterTypes,\n                                                                Object... arguments) throws Exception {\n        T mock = createNiceMock(type);\n        IExpectationSetters<T> expectationSetters = expectNiceNew(type, parameterTypes, arguments);\n        if (expectationSetters != null) {\n            expectationSetters.andReturn(mock);\n        }\n        return mock;\n    }\n\n    /**\n     * Convenience method for createStrictMock followed by expectNew.\n     *\n     * @param type      The class that should be mocked.\n     * @param arguments The constructor arguments.\n     * @return A mock object of the same type as the mock.\n     * @throws Exception\n     */\n    public static synchronized <T> T createStrictMockAndExpectNew(Class<T> type, Object... arguments) throws Exception {\n        T mock = createStrictMock(type);\n        expectStrictNew(type, arguments).andReturn(mock);\n        return mock;\n    }\n\n    /**\n     * Convenience method for createStrictMock followed by expectNew when\n     * PowerMock cannot determine which constructor to use automatically. This\n     * happens when you have one constructor taking a primitive type and another\n     * one taking the wrapper type of the primitive. For example\n     * {@code int} and {@code Integer}.\n     *\n     * @param type           The class that should be mocked.\n     * @param parameterTypes The constructor parameter types.\n     * @param arguments      The constructor arguments.\n     * @return A mock object of the same type as the mock.\n     * @throws Exception\n     */\n    public static synchronized <T> T createStrictMockAndExpectNew(Class<T> type, Class<?>[] parameterTypes,\n                                                                  Object... arguments) throws Exception {\n        T mock = createStrictMock(type);\n        expectStrictNew(type, parameterTypes, arguments).andReturn(mock);\n        return mock;\n    }\n\n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock. Note that you must replay\n     * the class when using this method since this behavior is part of the class\n     * mock.\n     * <p/>\n     * Use this method when you need to specify parameter types for the\n     * constructor when PowerMock cannot determine which constructor to use\n     * automatically. In most cases you should use\n     * {@link #expectNew(Class, Object...)} instead.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Class<?>[] parameterTypes,\n                                                                    Object... arguments) throws Exception {\n        return doExpectNew(type, new DefaultMockStrategy(), parameterTypes, arguments);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    private static <T> IExpectationSetters<T> doExpectNew(Class<T> type, MockStrategy mockStrategy,\n                                                          Class<?>[] parameterTypes, Object... arguments) throws Exception {\n        if (type == null) {\n            throw new IllegalArgumentException(\"type cannot be null\");\n        } else if (mockStrategy == null) {\n            throw new IllegalArgumentException(\"Internal error: Mock strategy cannot be null\");\n        }\n\n        final boolean isNiceMock = mockStrategy instanceof NiceMockStrategy;\n\n        final Class<T> unmockedType = (Class<T>) WhiteboxImpl.getOriginalUnmockedType(type);\n        if (!isNiceMock) {\n            if (parameterTypes == null) {\n                WhiteboxImpl.findUniqueConstructorOrThrowException(type, arguments);\n            } else {\n                WhiteboxImpl.getConstructor(unmockedType, parameterTypes);\n            }\n        }\n\n        /*\n           * Check if this type has been mocked before\n           */\n        NewInvocationControl<IExpectationSetters<T>> newInvocationControl = (NewInvocationControl<IExpectationSetters<T>>) MockRepository\n                .getNewInstanceControl(unmockedType);\n        if (newInvocationControl == null) {\n            InvocationSubstitute<T> mock = doMock(InvocationSubstitute.class, false, mockStrategy, null,\n                    (Method[]) null);\n            newInvocationControl = new EasyMockNewInvocationControl<T>(mock, type);\n            MockRepository.putNewInstanceControl(type, newInvocationControl);\n            MockRepository.addObjectsToAutomaticallyReplayAndVerify(WhiteboxImpl.getOriginalUnmockedType(type));\n        }\n\n        if (isNiceMock && (arguments == null || arguments.length == 0)) {\n            return null;\n        }\n        return newInvocationControl.expectSubstitutionLogic(arguments);\n    }\n\n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock. Note that you must replay\n     * the class when using this method since this behavior is part of the class\n     * mock.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Object... arguments)\n            throws Exception {\n        return doExpectNew(type, new DefaultMockStrategy(), null, arguments);\n    }\n\n    /**\n     * Allows specifying expectations on new invocations for private member\n     * (inner) classes, local or anonymous classes. For example you might want\n     * to throw an exception or return a mock. Note that you must replay the\n     * class when using this method since this behavior is part of the class\n     * mock.\n     *\n     * @param fullyQualifiedName The fully-qualified name of the inner/local/anonymous type to\n     *                           expect.\n     * @param arguments          Optional number of arguments.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> IExpectationSetters<T> expectNew(String fullyQualifiedName, Object... arguments)\n            throws Exception {\n        final Class<?> forName = Class.forName(fullyQualifiedName);\n        return (IExpectationSetters<T>) doExpectNew(forName, new DefaultMockStrategy(), null, arguments);\n    }\n\n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock.\n     * <p/>\n     * This method checks the order of constructor invocations.\n     * <p/>\n     * Note that you must replay the class when using this method since this\n     * behavior is part of the class mock.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectStrictNew(Class<T> type, Object... arguments)\n            throws Exception {\n        return doExpectNew(type, new StrictMockStrategy(), null, arguments);\n    }\n\n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock. Note that you must replay\n     * the class when using this method since this behavior is part of the class\n     * mock.\n     * <p/>\n     * This method checks the order of constructor invocations.\n     * <p/>\n     * Use this method when you need to specify parameter types for the\n     * constructor when PowerMock cannot determine which constructor to use\n     * automatically. In most cases you should use\n     * {@link #expectNew(Class, Object...)} instead.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectStrictNew(Class<T> type, Class<?>[] parameterTypes,\n                                                                          Object... arguments) throws Exception {\n        return doExpectNew(type, new StrictMockStrategy(), parameterTypes, arguments);\n    }\n\n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock.\n     * <p/>\n     * This method allows any number of calls to a new constructor without\n     * throwing an exception.\n     * <p/>\n     * Note that you must replay the class when using this method since this\n     * behavior is part of the class mock.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectNiceNew(Class<T> type, Object... arguments)\n            throws Exception {\n        return doExpectNew(type, new NiceMockStrategy(), null, arguments);\n    }\n\n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock. Note that you must replay\n     * the class when using this method since this behavior is part of the class\n     * mock.\n     * <p/>\n     * This method allows any number of calls to a new constructor without\n     * throwing an exception.\n     * <p/>\n     * Use this method when you need to specify parameter types for the\n     * constructor when PowerMock cannot determine which constructor to use\n     * automatically. In most cases you should use\n     * {@link #expectNew(Class, Object...)} instead.\n     */\n    public static synchronized <T> IExpectationSetters<T> expectNiceNew(Class<T> type, Class<?>[] parameterTypes,\n                                                                        Object... arguments) throws Exception {\n        return doExpectNew(type, new NiceMockStrategy(), parameterTypes, arguments);\n    }\n\n    /**\n     * Suppress constructor calls on specific constructors only.\n     *\n     * @deprecated Use {@link #suppress(Constructor[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressConstructor(Constructor<?>... constructors) {\n        SuppressCode.suppressConstructor(constructors);\n    }\n\n    /**\n     * This method can be used to suppress the code in a specific constructor.\n     *\n     * @param clazz          The class where the constructor is located.\n     * @param parameterTypes The parameter types of the constructor to suppress.\n     * @deprecated Use {@link #suppress(Constructor)} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressSpecificConstructor(Class<?> clazz, Class<?>... parameterTypes) {\n        SuppressCode.suppressSpecificConstructor(clazz, parameterTypes);\n    }\n\n    /**\n     * Suppress all constructors in the given class and it's super classes.\n     *\n     * @param classes The classes whose constructors will be suppressed.\n     * @deprecated Use {@link #suppress(Constructor[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressConstructor(Class<?>... classes) {\n        SuppressCode.suppressConstructor(classes);\n    }\n\n    /**\n     * Suppress all constructors in the given class.\n     *\n     * @param clazz                      The classes whose constructors will be suppressed.\n     * @param excludePrivateConstructors optionally keep code in private constructors\n     * @deprecated Use {@link #suppress(Constructor[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressConstructor(Class<?> clazz, boolean excludePrivateConstructors) {\n        SuppressCode.suppressConstructor(clazz, excludePrivateConstructors);\n    }\n\n    /**\n     * Suppress specific fields. This works on both instance methods and static\n     * methods. Note that replay and verify are not needed as this is not part\n     * of a mock behavior.\n     *\n     * @deprecated Use {@link #suppress(Field[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressField(Field... fields) {\n        SuppressCode.suppressField(fields);\n    }\n\n    /**\n     * Suppress all fields for these classes.\n     *\n     * @deprecated Use {@link #suppress(Field[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressField(Class<?>[] classes) {\n        SuppressCode.suppressField(classes);\n    }\n\n    /**\n     * Suppress multiple methods for a class.\n     *\n     * @param clazz      The class whose methods will be suppressed.\n     * @param fieldNames The names of the methods that'll be suppressed. If field names\n     *                   are empty, <i>all</i> fields in the supplied class will be\n     *                   suppressed.\n     * @deprecated Use {@link #suppress(Field)} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressField(Class<?> clazz, String... fieldNames) {\n        SuppressCode.suppressField(clazz, fieldNames);\n    }\n\n    /**\n     * Suppress specific method calls on all types containing this method. This\n     * works on both instance methods and static methods. Note that replay and\n     * verify are not needed as this is not part of a mock behavior.\n     *\n     * @deprecated Use {@link #suppress(Method[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressMethod(Method... methods) {\n        SuppressCode.suppressMethod(methods);\n    }\n\n    /**\n     * Suppress all methods for these classes.\n     *\n     * @param cls               The first class whose methods will be suppressed.\n     * @param additionalClasses Additional classes whose methods will be suppressed.\n     * @deprecated Use {@link #suppress(Method[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressMethod(Class<?> cls, Class<?>... additionalClasses) {\n        SuppressCode.suppressMethod(cls, additionalClasses);\n    }\n\n    /**\n     * Suppress all methods for these classes.\n     *\n     * @param classes Classes whose methods will be suppressed.\n     * @deprecated Use {@link #suppress(Method[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressMethod(Class<?>[] classes) {\n        SuppressCode.suppressMethod(classes);\n    }\n\n    /**\n     * Suppress multiple methods for a class.\n     *\n     * @param clazz                 The class whose methods will be suppressed.\n     * @param methodName            The first method to be suppress in class {@code clazz}.\n     * @param additionalMethodNames Additional methods to suppress in class {@code clazz}.\n     * @deprecated Use {@link #suppress(Method[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressMethod(Class<?> clazz, String methodName, String... additionalMethodNames) {\n        SuppressCode.suppressMethod(clazz, methodName, additionalMethodNames);\n    }\n\n    /**\n     * Suppress multiple methods for a class.\n     *\n     * @param clazz       The class whose methods will be suppressed.\n     * @param methodNames Methods to suppress in class {@code clazz}.\n     * @deprecated Use {@link #suppress(Method[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressMethod(Class<?> clazz, String[] methodNames) {\n        SuppressCode.suppressMethod(clazz, methodNames);\n    }\n\n    /**\n     * Suppress all methods for this class.\n     *\n     * @param clazz                 The class which methods will be suppressed.\n     * @param excludePrivateMethods optionally not suppress private methods\n     * @deprecated Use {@link #suppress(Method[])} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressMethod(Class<?> clazz, boolean excludePrivateMethods) {\n        SuppressCode.suppressMethod(clazz, excludePrivateMethods);\n    }\n\n    /**\n     * Suppress a specific method call. Use this for overloaded methods.\n     *\n     * @deprecated Use {@link #suppress(Method)} instead.\n     */\n    @Deprecated\n    public static synchronized void suppressMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) {\n        SuppressCode.suppressMethod(clazz, methodName, parameterTypes);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    private static <T> T doMock(Class<T> type, boolean isStatic, MockStrategy mockStrategy,\n                                ConstructorArgs constructorArgs, Method... methods) {\n        if (type == null) {\n            throw new IllegalArgumentException(\"The class to mock cannot be null\");\n        }\n\n        /*\n         * Clear the EasyMock state after the test method is executed.\n         */\n        MockRepository.addAfterMethodRunner(new Runnable() {\n            @Override\n            public void run() {\n                LastControl.reportLastControl(null);\n            }\n        });\n\n        IMocksControl control = mockStrategy.createMockControl(type);\n        MockRepository.addAfterMethodRunner(new EasyMockStateCleaner());\n        T mock;\n        if (type.isInterface()) {\n            mock = control.createMock(type);\n        } else if (type.getName().startsWith(\"java.\") && Modifier.isFinal(type.getModifiers())) {\n            Class<?> replicaType = createReplicaType(type, isStatic, constructorArgs);\n            final Object replica = doCreateMock(replicaType, constructorArgs, control, methods);\n            control = mockStrategy.createMockControl(replicaType);\n            MockInvocationHandler h = new MockInvocationHandler((MocksControl) control);\n            final Set<Method> methodsToMock = toSet(methods);\n            if (isStatic) {\n                MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl<Object>(h,\n                        methodsToMock, replica));\n                MockRepository.addObjectsToAutomaticallyReplayAndVerify(type);\n                return null;\n            } else {\n                final T newInstance;\n                if (constructorArgs == null) {\n                    newInstance = Whitebox.newInstance(type);\n                    DefaultFieldValueGenerator.fillWithDefaultValues(newInstance);\n                } else {\n                    try {\n                        newInstance = (T) constructorArgs.getConstructor().newInstance(constructorArgs.getInitArgs());\n                    } catch (Exception e) {\n                        throw new RuntimeException(\"Internal error\", e);\n                    }\n                }\n                MockRepository.putInstanceMethodInvocationControl(newInstance,\n                        new EasyMockMethodInvocationControl<Object>(h, methodsToMock, replica));\n                if (!(newInstance instanceof InvocationSubstitute<?>)) {\n                    MockRepository.addObjectsToAutomaticallyReplayAndVerify(newInstance);\n                }\n                return newInstance;\n            }\n        } else {\n            mock = doCreateMock(type, constructorArgs, control, methods);\n        }\n        MockInvocationHandler h = new MockInvocationHandler((MocksControl) control);\n        final Set<Method> methodsToMock = toSet(methods);\n        if (isStatic) {\n            MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl<T>(h,\n                    methodsToMock, mock));\n            MockRepository.addObjectsToAutomaticallyReplayAndVerify(type);\n        } else {\n            MockRepository.putInstanceMethodInvocationControl(mock, new EasyMockMethodInvocationControl<T>(h,\n                    methodsToMock));\n            if (!(mock instanceof InvocationSubstitute<?>)) {\n                MockRepository.addObjectsToAutomaticallyReplayAndVerify(mock);\n            }\n        }\n        ClassLoader classLoader = mock.getClass().getClassLoader();\n        if (classLoader instanceof MockClassLoader) {\n            ((MockClassLoader) classLoader).cache(mock.getClass());\n        }\n        return mock;\n    }\n\n    private static <T> Class<?> createReplicaType(Class<T> type, boolean isStatic, ConstructorArgs constructorArgs) {\n        final ClassReplicaCreator classReplicaCreator = new ClassReplicaCreator();\n        final Class<?> replicaType;\n        if (isStatic || constructorArgs == null) {\n            replicaType = classReplicaCreator.createClassReplica(type);\n        } else {\n            try {\n                replicaType = classReplicaCreator.createInstanceReplica(constructorArgs.getConstructor().newInstance(\n                        constructorArgs.getInitArgs()));\n            } catch (RuntimeException e) {\n                throw e;\n            } catch (InvocationTargetException e) {\n                Throwable targetException = e.getTargetException();\n                if (targetException instanceof RuntimeException) {\n                    throw (RuntimeException) targetException;\n                }\n                throw new RuntimeException(e);\n            } catch (Exception e) {\n                throw new RuntimeException(e);\n            }\n\n        }\n        return replicaType;\n    }\n\n    private static <T> T doCreateMock(Class<T> type, ConstructorArgs constructorArgs, final IMocksControl control,\n                                      Method... methods) {\n        T mock;\n        MocksControl mocksControl = ((MocksControl) control);\n        if (constructorArgs == null) {\n            if (methods == null) {\n                mock = mocksControl.createMock(type);\n            } else {\n                mock = mocksControl.createMock(null, type, null, methods);\n            }\n        } else {\n            if (methods == null) {\n                mock = mocksControl.createMock(null, type, constructorArgs);\n            } else {\n                mock = mocksControl.createMock(null, type, constructorArgs, methods);\n            }\n        }\n        return mock;\n    }\n\n    private static Set<Method> toSet(Method[] methods) {\n        return methods == null ? null : new HashSet<Method>(Arrays.asList(methods));\n    }\n\n    private static Class<?>[] mergeArgumentTypes(Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) {\n        if (firstArgumentType == null) {\n            return additionalArgumentTypes == null ? new Class<?>[0] : additionalArgumentTypes;\n        } else if (additionalArgumentTypes == null) {\n            additionalArgumentTypes = new Class<?>[0];\n        }\n        final Class<?>[] argumentTypes = new Class[additionalArgumentTypes.length + 1];\n        argumentTypes[0] = firstArgumentType;\n        if (additionalArgumentTypes.length != 0) {\n            System.arraycopy(additionalArgumentTypes, 0, argumentTypes, 1, additionalArgumentTypes.length);\n        }\n        return argumentTypes;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    private static <T> IExpectationSetters<T> doExpectPrivate(Object instance, Method methodToExpect,\n                                                              Object... arguments) throws Exception {\n        WhiteboxImpl.performMethodInvocation(instance, methodToExpect, arguments);\n        return (IExpectationSetters<T>) org.easymock.EasyMock.expectLastCall();\n    }\n\n    private static synchronized void replay(Class<?>... types) {\n        for (Class<?> type : types) {\n            final MethodInvocationControl invocationHandler = MockRepository.getStaticMethodInvocationControl(type);\n            if (invocationHandler != null) {\n                invocationHandler.replay();\n            }\n\n            NewInvocationControl<?> newInvocationControl = MockRepository.getNewInstanceControl(type);\n            if (newInvocationControl != null) {\n                newInvocationControl.replay();\n            }\n        }\n    }\n\n    /**\n     * Note: doesn't clear PowerMock state.\n     */\n    private static synchronized void verifyClass(Class<?>... types) {\n        for (Class<?> type : types) {\n            final EasyMockMethodInvocationControl invocationHandler = (EasyMockMethodInvocationControl) MockRepository.getStaticMethodInvocationControl(type);\n            if (invocationHandler != null) {\n                invocationHandler.verify();\n            }\n            EasyMockNewInvocationControl<?> newInvocationControl = (EasyMockNewInvocationControl<?>) MockRepository.getNewInstanceControl(type);\n            if (newInvocationControl != null) {\n                try {\n                    newInvocationControl.verify();\n                } catch (AssertionError e) {\n                    NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type);\n                }\n            }\n        }\n    }\n\n    private static boolean isNiceReplayAndVerifyMode() {\n        final Boolean mode = MockRepository.getAdditionalState(NICE_REPLAY_AND_VERIFY_KEY);\n        return mode != null && mode;\n    }\n\n    /**\n     * Clears the state in LastControl that deals with MocksControl.\n     */\n    private static class EasyMockStateCleaner implements Runnable {\n\n        @Override\n        public void run() {\n            LastControl.reportLastControl(null);\n            clearStateFromOtherClassLoaders();\n        }\n\n        private void clearStateFromOtherClassLoaders() {\n            for (ClassLoader cl : classloadersToClear()) {\n                try {\n                    final Class<?> lastControlClassByCL = Class.forName(LastControl.class.getName(), false, cl);\n                    final Class<?> mocksControlClassByCL = Class.forName(MocksControl.class.getName(), false, cl);\n                    final Method reportLastControl = lastControlClassByCL.getMethod(\"reportLastControl\", mocksControlClassByCL);\n                    reportLastControl.invoke(lastControlClassByCL, new Object[]{null});\n                } catch (Exception e) {\n                    // Should never happen\n                    throw new RuntimeException(\"Failed to clean up state\", e);\n\n                }\n            }\n        }\n\n        private Iterable<ClassLoader> classloadersToClear() {\n            List<ClassLoader> loaders = new ArrayList<ClassLoader>();\n            final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();\n            final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();\n            if (classFoundInClassloader(LastControl.class, systemClassLoader)) {\n                loaders.add(systemClassLoader);\n            }\n            if (classFoundInClassloader(LastControl.class, contextClassLoader)) {\n                loaders.add(contextClassLoader);\n            }\n            return loaders;\n        }\n\n        private boolean classFoundInClassloader(Class<?> cls, ClassLoader classLoader) {\n            try {\n                Class.forName(cls.getName(), false, classLoader);\n                return true;\n            } catch (ClassNotFoundException e) {\n                return false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/Mock.java",
    "content": "package org.powermock.api.easymock.annotation;\n\nimport org.powermock.core.classloader.annotations.PowerMockListener;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * This annotation can be placed on those fields in your test class that should\n * be mocked. This eliminates the need to setup and tear-down mocks manually\n * which minimizes repetitive test code and makes the test more readable. In\n * order for PowerMock to control the life-cycle of the mocks you must supply\n * the {@link PowerMockListener} annotation to the class-level of the test case.\n * For example:\n * \n * <pre>\n * ...\n * &#064;PowerMockListener(AnnotationEnabler.class)\n * public class PersonServiceTest {\n * \n * \t&#064;Mock\n * \tprivate PersonDao personDaoMock;\n * \n * \tprivate PersonService classUnderTest;\n * \n * \t&#064;Before\n * \tpublic void setUp() {\n * \t\tclassUnderTest = new PersonService(personDaoMock);\n * \t}\n *  ...\n * }\n * </pre>\n * <p>\n * \n * Note that you can also create partial mocks by using the annotation. Let's\n * say that the PersonService has a method called \"getPerson\" and another method\n * called \"savePerson\" and these are the only two methods that you'd like to\n * mock. Rewriting the previous example to accommodate this will give us the\n * following test:\n * \n * <pre>\n * ...\n * &#064;PowerMockListener(AnnotationEnabler.class)\n * public class PersonServiceTest {\n * \n * \t&#064;Mock({&quot;getPerson&quot;, &quot;savePerson&quot;})\n * \tprivate PersonDao personDaoMock;\n * \n * \tprivate PersonService classUnderTest;\n * \n * \t&#064;Before\n * \tpublic void setUp() {\n * \t\tclassUnderTest = new PersonService(personDaoMock);\n * \t}\n *  ...\n * }\n * </pre>\n * <p>\n */\n\n@Target( { ElementType.FIELD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\npublic @interface Mock {\n\tString[] value() default \"\";\n\n\t/**\n\t * Name of the test subject field to which this mock will be assigned. Use to disambiguate the case where\n     * a mock may be assigned to multiple fields of the same type.\n\t * When set, this mock will be assigned to the given field name in any test subject with a matching field name.\n\t * If not set, injection is to all type-compatible fields in all test subjects.\n\t * A given field name may only be used once, and there must be a matching field in at least one test subject.\n\t *\n\t * @return name of the field to inject to\n\t **/\n\tString fieldName() default \"\";\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/MockNice.java",
    "content": "package org.powermock.api.easymock.annotation;\n\nimport org.powermock.core.classloader.annotations.PowerMockListener;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * This annotation can be placed on those fields in your test class that should\n * be mocked in a nice manner (i.e. by default allows all method calls and\n * returns appropriate empty values (0, {@code null} or {@code false}\n * )). This eliminates the need to setup and tear-down mocks manually which\n * minimizes repetitive test code and makes the test more readable. In order for\n * PowerMock to control the life-cycle of the mocks you must supply the\n * {@link PowerMockListener} annotation to the class-level of the test case. For\n * example when using the EasyMock API:\n * \n * <pre>\n * &#064;PowerMockListener(EasyMockAnnotationEnabler.class)\n * public class PersonServiceTest {\n * \n * \t&#064;MockNice\n * \tprivate PersonDao personDaoMock;\n * \n * \tprivate PersonService classUnderTest;\n * \n * \t&#064;Before\n * \tpublic void setUp() {\n * \t\tclassUnderTest = new PersonService(personDaoMock);\n * \t}\n *  ...\n * }\n * </pre>\n * <p>\n * \n * Note that you can also create partial mocks by using the annotation. Let's\n * say that the PersonService has a method called \"getPerson\" and another method\n * called \"savePerson\" and these are the only two methods that you'd like to\n * mock. Rewriting the previous example to accommodate this will give us the\n * following test:\n * \n * <pre>\n * &#064;PowerMockListener(EasyMockAnnotationEnabler.class)\n * public class PersonServiceTest {\n * \n * \t&#064;MockNice({&quot;getPerson&quot;, &quot;savePerson&quot;})\n * \tprivate PersonDao personDaoMock;\n * \n * \tprivate PersonService classUnderTest;\n * \n * \t&#064;Before\n * \tpublic void setUp() {\n * \t\tclassUnderTest = new PersonService(personDaoMock);\n * \t}\n *  ...\n * }\n * </pre>\n * <p>\n * \n */\n\n@Target( { ElementType.FIELD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface MockNice {\n\tString[] value() default \"\";\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/MockStrict.java",
    "content": "package org.powermock.api.easymock.annotation;\n\nimport org.powermock.core.classloader.annotations.PowerMockListener;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * This annotation can be placed on those fields in your test class that should\n * be mocked in a strict manner (i.e. the order of method calls are checked).\n * This eliminates the need to setup and tear-down mocks manually which\n * minimizes repetitive test code and makes the test more readable. In order for\n * PowerMock to control the life-cycle of the mocks you must supply the\n * {@link PowerMockListener} annotation to the class-level of the test case. For\n * example when using the EasyMock API:\n * \n * <pre>\n * &#064;PowerMockListener(EasyMockAnnotationEnabler.class)\n * public class PersonServiceTest {\n * \n * \t&#064;MockStrict\n * \tprivate PersonDao personDaoMock;\n * \n * \tprivate PersonService classUnderTest;\n * \n * \t&#064;Before\n * \tpublic void setUp() {\n * \t\tclassUnderTest = new PersonService(personDaoMock);\n * \t}\n *  ...\n * }\n * </pre>\n * <p>\n * \n * Note that you can also create partial mocks by using the annotation. Let's\n * say that the PersonService has a method called \"getPerson\" and another method\n * called \"savePerson\" and these are the only two methods that you'd like to\n * mock. Rewriting the previous example to accommodate this will give us the\n * following test:\n * \n * <pre>\n * &#064;PowerMockListener(EasyMockAnnotationEnabler.class)\n * public class PersonServiceTest {\n * \n * \t&#064;MockStrict({&quot;getPerson&quot;, &quot;savePerson&quot;})\n * \tprivate PersonDao personDaoMock;\n * \n * \tprivate PersonService classUnderTest;\n * \n * \t&#064;Before\n * \tpublic void setUp() {\n * \t\tclassUnderTest = new PersonService(personDaoMock);\n * \t}\n *  ...\n * }\n * </pre>\n * <p>\n * \n */\n\n@Target( { ElementType.FIELD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface MockStrict {\n\tString[] value() default \"\";\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/EasyMockMethodInvocationControl.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock.internal.invocationcontrol;\n\nimport org.easymock.MockType;\nimport org.easymock.internal.MockInvocationHandler;\nimport org.easymock.internal.MocksControl;\nimport org.powermock.core.spi.MethodInvocationControl;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\n/**\n * The default implementation of the {@link MethodInvocationControl} interface.\n */\npublic class EasyMockMethodInvocationControl<T> implements MethodInvocationControl {\n\n    private MockInvocationHandler invocationHandler;\n\n    private Set<Method> mockedMethods;\n\n    private T mockInstance;\n\n    private boolean hasReplayed;\n    private boolean hasVerified;\n\n    /**\n     * Initializes internal state.\n     *\n     * @param invocationHandler The mock invocation handler to be associated with this\n     *                          instance.\n     * @param methodsToMock     The methods that are mocked for this instance. If\n     *                          {@code methodsToMock} is null all methods for the\n     *                          {@code invocationHandler} are considered to be mocked.\n     * @param mockInstance      The actual mock instance. May be {@code null}. Even\n     *                          though the mock instance may not be used it's needed to keep a\n     *                          reference to this object otherwise it may be garbage collected\n     *                          in some situations. For example when mocking static methods we\n     *                          don't return the mock object and thus it will be garbage\n     *                          collected (and thus the finalize method will be invoked which\n     *                          will be caught by the proxy and the test will fail because we\n     *                          haven't setup expectations for this method) because then that\n     *                          object has no reference. In order to avoid this we keep a\n     *                          reference to this instance here.\n     */\n    public EasyMockMethodInvocationControl(MockInvocationHandler invocationHandler, Set<Method> methodsToMock, T mockInstance) {\n        if (invocationHandler == null) {\n            throw new IllegalArgumentException(\"Invocation Handler cannot be null.\");\n        }\n\n        this.invocationHandler = invocationHandler;\n        this.mockedMethods = methodsToMock;\n        this.mockInstance = mockInstance;\n    }\n\n    /**\n     * Initializes internal state.\n     *\n     * @param invocationHandler The mock invocation handler to be associated with this\n     *                          instance.\n     * @param methodsToMock     The methods that are mocked for this instance. If\n     *                          {@code methodsToMock} is null all methods for the\n     *                          {@code invocationHandler} are considered to be mocked.\n     */\n    public EasyMockMethodInvocationControl(MockInvocationHandler invocationHandler, Set<Method> methodsToMock) {\n        this(invocationHandler, methodsToMock, null);\n    }\n\n    @Override\n    public boolean isMocked(Method method) {\n        return mockedMethods == null || (mockedMethods != null && mockedMethods.contains(method));\n    }\n\n    @Override\n    public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {\n        return invocationHandler.invoke(mockInstance == null ? proxy : mockInstance, method, arguments);\n    }\n\n    public MockType getMockType() {\n        final MocksControl control = invocationHandler.getControl();\n        if (WhiteboxImpl.getFieldsOfType(control, MockType.class).isEmpty()) {\n            // EasyMock is of version 3.2+\n            final MockType mockType = WhiteboxImpl.getInternalState(control, MockType.class);\n            switch (mockType) {\n                case DEFAULT:\n                    return MockType.DEFAULT;\n                case NICE:\n                    return MockType.NICE;\n                case STRICT:\n                    return MockType.STRICT;\n                default:\n                    throw new IllegalStateException(\"PowerMock doesn't seem to work with the used EasyMock version. Please report to the PowerMock mailing list\");\n            }\n        } else {\n            return WhiteboxImpl.getInternalState(control, MockType.class);\n        }\n    }\n\n    @Override\n    public synchronized Object replay(Object... mocks) {\n        // Silently ignore replay if someone has replayed the mock before.\n        if (!hasReplayed) {\n            invocationHandler.getControl().replay();\n            hasReplayed = true;\n        }\n        return null;\n    }\n\n    public synchronized Object verify(Object... mocks) {\n        // Silently ignore verify if someone has verified the mock before.\n        if (!hasVerified) {\n            invocationHandler.getControl().verify();\n            hasVerified = true;\n        }\n        return null;\n    }\n\n    @Override\n    public synchronized Object reset(Object... mocks) {\n        invocationHandler.getControl().reset();\n        hasReplayed = false;\n        hasVerified = false;\n        return null;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/EasyMockNewInvocationControl.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock.internal.invocationcontrol;\n\nimport org.easymock.EasyMock;\nimport org.easymock.IExpectationSetters;\nimport org.easymock.MockType;\nimport org.easymock.internal.MocksControl;\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.spi.NewInvocationControl;\nimport org.powermock.core.spi.support.InvocationSubstitute;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Constructor;\n\npublic class EasyMockNewInvocationControl<T> implements NewInvocationControl<IExpectationSetters<T>> {\n    private final InvocationSubstitute<T> substitute;\n    private final Class<T> subsitutionType;\n    private boolean hasReplayed;\n    private boolean hasVerified;\n\n    public EasyMockNewInvocationControl(InvocationSubstitute<T> substitute, Class<T> type) {\n        if (substitute == null) {\n            throw new IllegalArgumentException(\"Internal error: substitute cannot be null.\");\n        }\n        this.subsitutionType = type;\n        this.substitute = substitute;\n    }\n\n    @Override\n    public Object invoke(Class<?> type, Object[] args, Class<?>[] sig) throws Exception {\n        Constructor<?> constructor = WhiteboxImpl.getConstructor(type, sig);\n        if (constructor.isVarArgs()) {\n            /*\n             * Get the last argument because this contains the actual varargs\n             * arguments.\n             */\n            int length = constructor.getParameterTypes().length;\n            args = (Object[]) args[length-1];\n        }\n        try {\n            final MockType mockType = ((EasyMockMethodInvocationControl<?>) MockRepository.getInstanceMethodInvocationControl(substitute))\n                    .getMockType();\n            Object result = substitute.performSubstitutionLogic(args);\n\n            if (result == null) {\n                if (mockType == MockType.NICE) {\n                    result = EasyMock.createNiceMock(subsitutionType);\n                } else {\n                    throw new IllegalStateException(\"Must replay class \" + type.getName() + \" to get configured expectation.\");\n                }\n            }\n            return result;\n        } catch (AssertionError e) {\n            NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type);\n        }\n\n        // Won't happen\n        return null;\n    }\n\n    @Override\n    public IExpectationSetters<T> expectSubstitutionLogic(Object... arguments) throws Exception {\n        return EasyMock.expect(substitute.performSubstitutionLogic(arguments));\n    }\n\n    @Override\n    public synchronized Object replay(Object... mocks) {\n        if (!hasReplayed) {\n            EasyMock.replay(substitute);\n            hasReplayed = true;\n        }\n        return null;\n    }\n\n    public synchronized Object verify(Object... mocks) {\n        if (!hasVerified) {\n            EasyMock.verify(substitute);\n            hasVerified = true;\n        }\n        return null;\n    }\n\n    @Override\n    public synchronized Object reset(Object... mocks) {\n        EasyMock.reset(substitute);\n        hasReplayed = false;\n        hasVerified = false;\n        return null;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/NewInvocationControlAssertionError.java",
    "content": "package org.powermock.api.easymock.internal.invocationcontrol;\n\nimport org.powermock.core.spi.support.InvocationSubstitute;\n\nimport java.util.regex.Matcher;\n\npublic class NewInvocationControlAssertionError {\n    public static void throwAssertionErrorForNewSubstitutionFailure(AssertionError oldError, Class<?> type) {\n        /*\n         * We failed to verify the new substitution mock. This happens when, for\n         * example, the user has done something like\n         * expectNew(MyClass.class).andReturn(myMock).times(3) when in fact an\n         * instance of MyClass has been created less or more times than 3.\n         */\n        String message = oldError.getMessage();\n        final String newSubsitutionMethodName = InvocationSubstitute.class.getDeclaredMethods()[0].getName();\n        final String className = InvocationSubstitute.class.getSimpleName();\n        message = message.replaceAll(className+\".\"+newSubsitutionMethodName, Matcher.quoteReplacement(type.getName()));\n        message = message.replaceAll(\"method\", \"constructor\");\n\n        throw new AssertionError(message);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/MockStrategy.java",
    "content": "package org.powermock.api.easymock.internal.mockstrategy;\n\nimport org.easymock.IMocksControl;\n\npublic interface MockStrategy {\n\n\tIMocksControl createMockControl(Class<?> type);\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/AbstractMockStrategyBase.java",
    "content": "package org.powermock.api.easymock.internal.mockstrategy.impl;\n\nimport org.easymock.IMocksControl;\nimport org.easymock.internal.MocksControl;\nimport org.easymock.MockType;\nimport org.powermock.api.easymock.internal.mockstrategy.MockStrategy;\n\n/**\n * Base class that should be used by all mock strategies. Enables mocking of\n * signed classes.\n */\npublic abstract class AbstractMockStrategyBase implements MockStrategy {\n\n\tprivate final MockType mockType;\n\n\tpublic AbstractMockStrategyBase(MockType mockType) {\n\t\tif (mockType == null) {\n\t\t\tthrow new IllegalArgumentException(\"Internal error: mockType cannot be null\");\n\t\t}\n\t\tthis.mockType = mockType;\n\t}\n\n\t@Override\n\tpublic IMocksControl createMockControl(Class<?> type) {\n\t\treturn new MocksControl(mockType);\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/DefaultMockStrategy.java",
    "content": "package org.powermock.api.easymock.internal.mockstrategy.impl;\n\nimport org.easymock.MockType;\n\npublic class DefaultMockStrategy extends AbstractMockStrategyBase {\n\n\tpublic DefaultMockStrategy() {\n\t\tsuper(MockType.DEFAULT);\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/NiceMockStrategy.java",
    "content": "package org.powermock.api.easymock.internal.mockstrategy.impl;\n\nimport org.easymock.MockType;\n\npublic class NiceMockStrategy extends AbstractMockStrategyBase {\n\n\tpublic NiceMockStrategy() {\n\t\tsuper(MockType.NICE);\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/StrictMockStrategy.java",
    "content": "package org.powermock.api.easymock.internal.mockstrategy.impl;\n\nimport org.easymock.MockType;\n\npublic class StrictMockStrategy extends AbstractMockStrategyBase {\n\n\tpublic StrictMockStrategy() {\n\t\tsuper(MockType.STRICT);\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/AbstractEasyMockLogPolicyBase.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock.mockpolicies;\n\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.mockpolicies.support.LogPolicySupport;\n\nimport java.lang.reflect.Method;\n\nimport static org.easymock.EasyMock.makeThreadSafe;\nimport static org.powermock.api.easymock.PowerMock.createNiceMock;\n\n/**\n * A base class for EasyMock log policies.\n */\nabstract class AbstractEasyMockLogPolicyBase implements PowerMockPolicy {\n\n\t@Override\n\tpublic void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {\n\t\tsettings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(getFullyQualifiedNamesOfClassesToLoadByMockClassloader());\n\t}\n\n\t@Override\n\tpublic void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {\n\t\tLogPolicySupport support = new LogPolicySupport();\n\n\t\tMethod[] loggerFactoryMethods = support.getLoggerMethods(getLoggerFactoryClassName(), getLoggerMethodName(), getLogFrameworkName());\n\n\t\tClass<?> loggerType = null;\n\t\ttry {\n\t\t\tloggerType = support.getType(getLoggerClassToMock(), getLogFrameworkName());\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\n\t\tfinal Object loggerMock = createNiceMock(loggerType);\n\t\t// Allow the mock to be used in a multi-threaded environment\n\t\tmakeThreadSafe(loggerMock, true);\n\n\t\tfor (Method method : loggerFactoryMethods) {\n\t\t\tsettings.stubMethod(method, loggerMock);\n\t\t}\n\t}\n\n\t/**\n\t * @return The name of the methods in the Logger Factory that should return\n\t *         a mock upon invocation.\n\t */\n\tprotected abstract String getLoggerMethodName();\n\n\t/**\n\t * @return The fully-qualified class name of the Logger Factory that\n\t *         contains the methods that should return a mock upon invocation.\n\t */\n\tprotected abstract String getLoggerFactoryClassName();\n\n\t/**\n\t * @return The fully-qualified class name of the class that should be\n\t *         mocked. The mock instance of this class will then be returned\n\t *         each time a specified method in the Logger Factory is invoked.\n\t */\n\tprotected abstract String getLoggerClassToMock();\n\n\t/**\n\t * @return The name of the log framework. Used in error messages, for\n\t *         example if the {@link #getLoggerFactoryClassName()} cannot be\n\t *         found in the classpath.\n\t */\n\tprotected abstract String getLogFrameworkName();\n\n\t/**\n\t * @return The fully-qualified names of the classes that should be loaded by\n\t *         the mock classloader.\n\t */\n\tprotected abstract String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader();\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/JclMockPolicy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock.mockpolicies;\n\n\n/**\n * A Jakarta Commons-Logging (JCL) mock policy. This mock policy deals with\n * solving JCL related mocking issues. It takes care of loading all concerned\n * JCL classes through the correct class-loader and automatically prepares and\n * injects logger instances. This policy does the following:\n * <ol>\n * <li>Prepares all classes in the <tt>org.apache.commons.logging</tt> for test\n * as well as <tt>org.apache.log4j.Appender</tt> and\n * <tt>org.apache.log4j.xml.DOMConfigurator</tt>.</li>\n * <li>All calls to the\n * <tt>org.apache.commons.logging.LogFactory#getLog(..)</tt> methods are\n * intercepted and returns a nice mock of type\n * <tt>org.apache.commons.logging.Log</tt>.</li>\n * </ol>\n */\npublic class JclMockPolicy extends AbstractEasyMockLogPolicyBase {\n\n\t/**\n\t * Loads all log4j classes with the mock classloader.\n\t */\n\tprotected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {\n\t\treturn new String[] { \"org.apache.commons.logging.*\", \"org.apache.log4j.Appender\", \"org.apache.log4j.xml.DOMConfigurator\" };\n\t}\n\n\t@Override\n\tprotected String getLogFrameworkName() {\n\t\treturn \"commons-logging\";\n\t}\n\n\t@Override\n\tprotected String getLoggerClassToMock() {\n\t\treturn \"org.apache.commons.logging.Log\";\n\t}\n\n\t@Override\n\tprotected String getLoggerFactoryClassName() {\n\t\treturn \"org.apache.commons.logging.LogFactory\";\n\t}\n\n\t@Override\n\tprotected String getLoggerMethodName() {\n\t\treturn \"getLog\";\n\t}\n}"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/Log4jMockPolicy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock.mockpolicies;\n\n\n/**\n * A log4j mock policy. This mock policy deals with solving log4j related\n * mocking issues. It takes care of loading all concerned log4j classes through\n * the correct class-loader and automatically prepares and injects logger\n * instances. This policy does the following:\n * <ol>\n * <li>Prepares all log4j classes and interfaces for testing.</li>\n * <li>All calls to the <tt>org.apache.log4j.Logger#getLogger(..)</tt> methods\n * are intercepted and returns a nice mock of type\n * <tt>org.apache.log4j.Logger</tt>.</li>\n * </ol>\n */\npublic class Log4jMockPolicy extends AbstractEasyMockLogPolicyBase {\n\n\tprivate static final String LOGGER_CLASS = \"org.apache.log4j.Logger\";\n\n\t/**\n\t * Loads all log4j classes with the mock classloader.\n\t */\n\t@Override\n\tprotected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {\n\t\treturn new String[] { \"org.apache.log4j.*\" };\n\t}\n\n\t@Override\n\tprotected String getLogFrameworkName() {\n\t\treturn \"log4j\";\n\t}\n\n\t@Override\n\tprotected String getLoggerClassToMock() {\n\t\treturn LOGGER_CLASS;\n\t}\n\n\t@Override\n\tprotected String getLoggerFactoryClassName() {\n\t\treturn LOGGER_CLASS;\n\t}\n\n\t@Override\n\tprotected String getLoggerMethodName() {\n\t\treturn \"getLogger\";\n\t}\n}"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/Slf4jMockPolicy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock.mockpolicies;\n\n\n/**\n * An slf4j mock policy. This mock policy deals with solving slf4j related\n * mocking issues. It takes care of loading all concerned slf4j and log4j\n * classes through the correct class-loader and automatically prepares and\n * injects logger instances. This policy does the following:\n * <ol>\n * <li>Prepares <tt>org.apache.log4j.Appender</tt>,\n * <tt>org.slf4j.LoggerFactory</tt> and\n * <tt>org.apache.log4j.xml.DOMConfigurator</tt> for testing.</li>\n * <li>All calls to the <tt>org.slf4j.LoggerFactory#getLogger(..)</tt> methods\n * are intercepted and returns a nice mock of type <tt>org.slf4j.Logger</tt>.</li>\n * </ol>\n */\npublic class Slf4jMockPolicy extends AbstractEasyMockLogPolicyBase {\n\n\t@Override\n\tprotected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {\n\t\treturn new String[] { \"org.apache.log4j.Appender\", \"org.slf4j.LoggerFactory\", \"org.apache.log4j.xml.DOMConfigurator\" };\n\t}\n\n\t@Override\n\tprotected String getLogFrameworkName() {\n\t\treturn \"slf4j\";\n\t}\n\n\t@Override\n\tprotected String getLoggerClassToMock() {\n\t\treturn \"org.slf4j.Logger\";\n\t}\n\n\t@Override\n\tprotected String getLoggerFactoryClassName() {\n\t\treturn \"org.slf4j.LoggerFactory\";\n\t}\n\n\t@Override\n\tprotected String getLoggerMethodName() {\n\t\treturn \"getLogger\";\n\t}\n}"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/powermocklistener/AnnotationEnabler.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.easymock.powermocklistener;\n\nimport org.powermock.api.easymock.annotation.MockNice;\nimport org.powermock.api.easymock.annotation.MockStrict;\n\n/**\n * Before each test method all fields annotated with {@link org.powermock.api.easymock.annotation.Mock},\n * {@link MockNice} or {@link MockStrict} will have mock objects created for\n * them and injected to the fields.\n * \n * @deprecated Test Runners uses an annotation enabling listener per default\n *             since version 1.3. You should just remove this listener.\n */\n@Deprecated\npublic class AnnotationEnabler extends org.powermock.api.extension.listener.AnnotationEnabler {\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/InjectFieldSearcher.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension;\n\nimport org.powermock.api.extension.listener.MockMetadata;\n\nimport java.lang.reflect.Field;\n\n/**\n *\n */\npublic interface InjectFieldSearcher {\n    Field findField(Object instance, MockMetadata mockMetadata);\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/agent/JavaAgentFrameworkRegisterImpl.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.agent;\n\nimport org.powermock.core.agent.JavaAgentClassRegister;\nimport org.powermock.core.agent.JavaAgentFrameworkRegister;\n\n/**\n * Implementation of JavaAgentFrameworkRegister for EasyMock framework.\n */\npublic class JavaAgentFrameworkRegisterImpl implements JavaAgentFrameworkRegister {\n    @Override\n    public void set(JavaAgentClassRegister javaAgentClassRegister) {\n\n    }\n\n    @Override\n    public void clear() {\n\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.extension.listener;\n\nimport org.powermock.api.easymock.EasyMockConfiguration;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.api.easymock.annotation.MockNice;\nimport org.powermock.api.easymock.annotation.MockStrict;\nimport org.powermock.core.spi.listener.AnnotationEnablerListener;\nimport org.powermock.core.spi.support.AbstractPowerMockTestListenerBase;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\n/**\n * <p>\n * Before each test method all fields annotated with\n * {@link Mock}, {@link org.powermock.api.easymock.annotation.Mock}, {@link org.easymock.Mock}\n * {@link MockNice} or {@link MockStrict} will have mock objects created for\n * them and injected to the fields.\n * </p>\n * <p>\n * Also all fields annotated with {@link org.easymock.TestSubject} will be processed and mocks are injected to fields\n * object, if these fields not null.\n * </p>\n * <p>\n * It will only inject to fields that haven't been set before (i.e that are\n * {@code null}).\n * </p>\n *\n * @see org.powermock.api.easymock.annotation.Mock\n * @see org.easymock.Mock\n * @see org.easymock.TestSubject\n *\n */\n@SuppressWarnings({\"deprecation\", \"JavadocReference\"})\npublic class AnnotationEnabler extends AbstractPowerMockTestListenerBase implements AnnotationEnablerListener {\n\n\n    @SuppressWarnings(\"unchecked\")\n    public Class<? extends Annotation>[] getMockAnnotations() {\n        return new Class[]{Mock.class, MockNice.class, MockStrict.class};\n    }\n\n    @Override\n    public void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception {\n\n        EasyMockConfiguration easyMockConfiguration = EasyMockConfiguration.getConfiguration();\n\n        if (!easyMockConfiguration.isReallyEasyMock()) {\n            // Easymock API could be used as depends for JMock.\n            return;\n        }\n\n        // first emulate default EasyMockRunner behavior\n        if (easyMockConfiguration.isInjectMocksSupported()) {\n            Whitebox.invokeMethod(Class.forName(\"org.easymock.EasyMockSupport\"), \"injectMocks\", testInstance);\n        }\n\n        // then inject in empty fields mock created via PowerMock\n\n        getEasyMockAnnotationSupport(testInstance).injectMocks();\n    }\n\n    @SuppressWarnings(\"WeakerAccess\")\n    protected EasyMockAnnotationSupport getEasyMockAnnotationSupport(Object testInstance) {\n        return new EasyMockAnnotationSupport(testInstance);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationGlobalMetadata.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n *\n */\nclass AnnotationGlobalMetadata {\n\n    private final List<MockMetadata> qualifiedInjections = new ArrayList<MockMetadata>(5);\n\n    private final List<MockMetadata> unqualifiedInjections = new ArrayList<MockMetadata>(5);\n\n    private final Set<String> qualifiers = new HashSet<String>();\n\n    public List<MockMetadata> getQualifiedInjections() {\n        return qualifiedInjections;\n    }\n\n    public List<MockMetadata> getUnqualifiedInjections() {\n        return unqualifiedInjections;\n    }\n\n    public void add(List<MockMetadata> mocksMetadata) {\n        for (MockMetadata mockMetadata : mocksMetadata) {\n            add(mockMetadata);\n        }\n    }\n\n    private void add(MockMetadata mockMetadata) {\n\n        String qualifier = mockMetadata.getQualifier();\n\n        if (qualifier.length() != 0) {\n            blockDuplicateQualifiers(qualifier);\n            qualifiedInjections.add(mockMetadata);\n        } else {\n            unqualifiedInjections.add(mockMetadata);\n        }\n    }\n\n    private void blockDuplicateQualifiers(String qualifier) {\n        if (!qualifiers.add(qualifier)) {\n            throw new RuntimeException(String.format(\"At least two mocks have fieldName qualifier '%s'\", qualifier));\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreator.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport java.lang.reflect.Method;\n\n/**\n *\n */\ninterface AnnotationMockCreator {\n    Object createMockInstance(final Class<?> type, final Method[] methods);\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreatorFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport java.lang.reflect.Method;\n\nimport static org.powermock.api.easymock.PowerMock.createMock;\nimport static org.powermock.api.easymock.PowerMock.createNiceMock;\nimport static org.powermock.api.easymock.PowerMock.createStrictMock;\n\n/**\n *\n */\nclass AnnotationMockCreatorFactory {\n    public AnnotationMockCreator createDefaultMockCreator() {\n        return new AnnotationMockCreator() {\n            @Override\n            public Object createMockInstance(Class<?> type, Method[] methods) {\n                return createMock(type, methods);\n            }\n        };\n    }\n\n    public AnnotationMockCreator createNiceMockCreator() {\n        return new AnnotationMockCreator() {\n            @Override\n            public Object createMockInstance(Class<?> type, Method[] methods) {\n                return createNiceMock(type, methods);\n            }\n        };\n    }\n\n    public AnnotationMockCreator createStrictMockCreator() {\n        return new AnnotationMockCreator() {\n            @Override\n            public Object createMockInstance(Class<?> type, Method[] methods) {\n                return createStrictMock(type, methods);\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockMetadata.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Arrays;\n\n@SuppressWarnings(\"WeakerAccess\")\npublic class AnnotationMockMetadata implements MockMetadata {\n    private final Class<?> type;\n    private final Method[] methods;\n    private final String qualifier;\n    private final Class<? extends Annotation> annotation;\n    private final Annotation annotationInstance;\n    private final String fieldName;\n    private Object mock;\n    \n    public AnnotationMockMetadata(Class<? extends Annotation> annotation, Field field) throws\n            Exception {\n        this.annotation = annotation;\n        this.annotationInstance = field.getAnnotation(annotation);\n        this.type = field.getType();\n        this.fieldName = field.getName();\n        this.methods = getMethod();\n        this.qualifier = findQualifier();\n    }\n\n    private String findQualifier() {\n        String fieldName = \"\";\n        try {\n            fieldName = Whitebox.invokeMethod(annotationInstance, \"fieldName\");\n        } catch (Exception e) {\n            // do nothing, because it means that Mock annotation doesn't support qualifier. S\n            // ee org.easymock.Mock.fieldName\n        }\n\n        if (fieldName.length() == 0) {\n            return \"\";\n        } else {\n            return fieldName;\n        }\n    }\n    \n    @Override\n    public String getFieldName() {\n        return fieldName;\n    }\n    \n    @Override\n    public String getQualifier() {\n        return qualifier;\n    }\n\n    @Override\n    public Class<? extends Annotation> getAnnotation() {\n        return annotation;\n    }\n\n    @Override\n    public Class<?> getType() {\n        return type;\n    }\n\n    @Override\n    public Method[] getMethods() {\n        return methods;\n    }\n\n    private Method[] getMethod() throws Exception {\n\n        final String[] value = Whitebox.invokeMethod(annotationInstance, \"value\");\n        if (value.length != 1 || !\"\".equals(value[0])) {\n            return Whitebox.getMethods(type, value);\n        }\n        return null;\n    }\n\n    @Override\n    public Object getMock() {\n        return mock;\n    }\n\n    @Override\n    public void setMock(Object mock) {\n        this.mock = mock;\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) { return true; }\n        if (o == null || getClass() != o.getClass()) { return false; }\n\n        AnnotationMockMetadata that = (AnnotationMockMetadata) o;\n\n        if (type != null ? !type.equals(that.type) : that.type != null) { return false; }\n        // Probably incorrect - comparing Object[] arrays with Arrays.equals\n        return Arrays.equals(methods, that.methods) && (qualifier != null ? qualifier.equals(that.qualifier) : that.qualifier == null);\n\n    }\n\n    @Override\n    public int hashCode() {\n        int result = type != null ? type.hashCode() : 0;\n        result = 31 * result + Arrays.hashCode(methods);\n        result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0);\n        return result;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockScanner.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\nclass AnnotationMockScanner {\n    private final Class<? extends Annotation> annotation;\n\n    public AnnotationMockScanner(Class<? extends Annotation> annotation) {\n        this.annotation = annotation;\n    }\n\n    public List<MockMetadata> scan(Object instance) throws Exception {\n        final List<MockMetadata> mocksMetadata = new ArrayList<MockMetadata>();\n        final Set<Field> fields = getFields(instance);\n        for (Field field : fields) {\n            if (field.get(instance) != null) {\n                continue;\n            }\n            mocksMetadata.add(new AnnotationMockMetadata(annotation, field));\n        }\n        return mocksMetadata;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    private Set<Field> getFields(Object instance) {\n        final Set<Field> fields;\n        if (annotation != null) {\n            fields = Whitebox.getFieldsAnnotatedWith(instance, annotation);\n        }else{\n            fields = Whitebox.getAllInstanceFields(instance);\n        }\n        return fields;\n    }\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/DefaultInjectFieldSearcher.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport org.powermock.api.extension.InjectFieldSearcher;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Field;\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n *\n */\n@SuppressWarnings(\"unchecked\")\nclass DefaultInjectFieldSearcher implements InjectFieldSearcher {\n\n    @Override\n    public Field findField(Object instance, MockMetadata mockMetadata) {\n        Set<Field> candidates = Whitebox.getFieldsAnnotatedWith(instance, mockMetadata.getAnnotation());\n        if (candidates.size() == 1) {\n            return candidates.iterator().next();\n        }\n        candidates = filterByQualifier(candidates, mockMetadata.getQualifier());\n        if (candidates.size() == 1) {\n            return candidates.iterator().next();\n        }\n        candidates = filterByType(candidates, mockMetadata.getType());\n        if (candidates.size() == 1) {\n            return candidates.iterator().next();\n        }\n        candidates = filterByFieldName(candidates, mockMetadata.getFieldName());\n        if (candidates.size() == 1) {\n            return candidates.iterator().next();\n        }\n        return null;\n    }\n    \n    private Set<Field> filterByFieldName(final Set<Field> candidates, final String fieldName) {\n        if (fieldName == null || fieldName.length() == 0) {\n            return candidates;\n        }\n        return doFilterByQualifier(candidates, fieldName);\n    }\n    \n    private Set<Field> filterByType(Set<Field> candidates, Class<?> type) {\n        if (type == null) {\n            return candidates;\n        }\n        return doFilterByType(candidates, type);\n    }\n\n    private Set<Field> doFilterByType(Set<Field> candidates, Class<?> type) {\n        Set<Field> fields = new HashSet<Field>();\n        for (Field candidate : candidates) {\n            if (candidate.getType().isAssignableFrom(type)) {\n                fields.add(candidate);\n            }\n        }\n        return fields;\n    }\n\n    private Set<Field> filterByQualifier(Set<Field> candidates, String qualifier) {\n        if (qualifier == null || qualifier.length() == 0) {\n            return candidates;\n        }\n        return doFilterByQualifier(candidates, qualifier);\n    }\n\n    private Set<Field> doFilterByQualifier(Set<Field> candidates, String qualifier) {\n        Set<Field> fields = new HashSet<Field>();\n        for (Field candidate : candidates) {\n            if (candidate.getName().equals(qualifier)) {\n                fields.add(candidate);\n            }\n        }\n        return fields;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/EasyMockAnnotationSupport.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport org.powermock.api.easymock.EasyMockConfiguration;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.api.easymock.annotation.MockNice;\nimport org.powermock.api.easymock.annotation.MockStrict;\nimport org.powermock.api.extension.InjectFieldSearcher;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.util.List;\n\n/**\n * This class works like as {@link org.easymock.EasyMockSupport} and is used to create and inject mocks to\n * annotated fields of an instance of test class.\n *\n * @see Mock\n * @see org.easymock.Mock\n * @see org.easymock.TestSubject\n */\n@SuppressWarnings({\"WeakerAccess\", \"JavadocReference\"})\npublic class EasyMockAnnotationSupport {\n\n    private final Object testInstance;\n    private final AnnotationMockCreatorFactory annotationMockCreatorFactory;\n    private final AnnotationGlobalMetadata globalMetadata;\n    private final EasyMockConfiguration easyMockConfiguration;\n\n    public EasyMockAnnotationSupport(Object testInstance) {\n        this.testInstance = testInstance;\n        this.annotationMockCreatorFactory = new AnnotationMockCreatorFactory();\n        this.globalMetadata = new AnnotationGlobalMetadata();\n        this.easyMockConfiguration = EasyMockConfiguration.getConfiguration();\n    }\n\n    public void injectMocks() throws Exception {\n        injectStrictMocks();\n        injectNiceMocks();\n        injectDefaultMocks();\n        injectTestSubjectMocks();\n    }\n\n    protected void injectStrictMocks() throws Exception {\n        inject(testInstance, MockStrict.class, annotationMockCreatorFactory.createStrictMockCreator());\n    }\n\n    protected void injectNiceMocks() throws Exception {\n        inject(testInstance, MockNice.class, annotationMockCreatorFactory.createNiceMockCreator());\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    protected void injectDefaultMocks() throws Exception {\n        inject(testInstance, Mock.class, annotationMockCreatorFactory.createDefaultMockCreator());\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    protected void injectTestSubjectMocks() throws IllegalAccessException {\n        if (easyMockConfiguration.isTestSubjectSupported()) {\n            TestSubjectInjector testSubjectInjector = new TestSubjectInjector(testInstance, globalMetadata);\n            testSubjectInjector.injectTestSubjectMocks();\n        }\n    }\n\n\n    protected void inject(Object injectCandidateInstance, Class<? extends Annotation> annotation, AnnotationMockCreator mockCreator) throws Exception {\n\n        AnnotationMockScanner scanner = new AnnotationMockScanner(annotation);\n\n        List<MockMetadata> mocksMetadata = scanner.scan(injectCandidateInstance);\n        globalMetadata.add(mocksMetadata);\n\n        for (MockMetadata mockMetadata : mocksMetadata) {\n            injectMock(injectCandidateInstance, mockMetadata, mockCreator, new DefaultInjectFieldSearcher());\n        }\n\n\n    }\n\n    protected void injectMock(Object injectCandidateInstance, MockMetadata mockMetadata,\n                              AnnotationMockCreator mockCreator, InjectFieldSearcher fieldSearch) throws IllegalAccessException {\n        Object mock = createMock(mockCreator, mockMetadata);\n        Field field = fieldSearch.findField(injectCandidateInstance, mockMetadata);\n        if (field != null && mock != null) {\n            field.setAccessible(true);\n            field.set(injectCandidateInstance, mock);\n        }\n    }\n\n\n    protected Object createMock(AnnotationMockCreator mockCreator, MockMetadata mockMetadata) {\n        if (mockMetadata.getMock() == null) {\n            Object mock = mockCreator.createMockInstance(mockMetadata.getType(), mockMetadata.getMethods());\n            mockMetadata.setMock(mock);\n        }\n        return mockMetadata.getMock();\n    }\n\n\n}"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/MockMetadata.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\n/**\n *\n */\npublic interface MockMetadata {\n    String getFieldName();\n    \n    String getQualifier();\n\n    Class<? extends Annotation> getAnnotation();\n\n    Class<?> getType();\n\n    Method[] getMethods();\n\n    Object getMock();\n\n    void setMock(Object mock);\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/TestSubjectInjector.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.extension.listener;\n\nimport org.easymock.Mock;\nimport org.easymock.TestSubject;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Field;\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * The class injects mocks created with {@link Mock}, {@link org.powermock.api.easymock.annotation.Mock}\n * to fields of objects which is annotated with {@link TestSubject}\n * @see TestSubject\n * @since 1.6.5\n */\n@SuppressWarnings({\"deprecation\", \"WeakerAccess\"})\nclass TestSubjectInjector {\n\n    private final Object testInstance;\n    private final AnnotationGlobalMetadata globalMetadata;\n\n    public TestSubjectInjector(Object testInstance, AnnotationGlobalMetadata globalMetadata) {\n\n        this.testInstance = testInstance;\n        this.globalMetadata = globalMetadata;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    protected void injectTestSubjectMocks() throws IllegalAccessException {\n\n        Set<Field> testSubjectFields = Whitebox.getFieldsAnnotatedWith(testInstance, TestSubject.class);\n        for (Field testSubjectField : testSubjectFields) {\n            Object testSubject = testSubjectField.get(testInstance);\n            if (testSubject == null) {\n                throw new NullPointerException(\"Have you forgotten to instantiate \" + testSubjectField.getName() + \"?\");\n            }\n            injectTestSubjectFields(testSubject);\n\n        }\n    }\n\n    protected void injectTestSubjectFields(Object testSubject) throws IllegalAccessException {\n        Set<Field> targetFields = new HashSet<Field>(Whitebox.getAllInstanceFields(testSubject));\n        targetFields = injectByName(targetFields, testSubject);\n        injectByType(targetFields, testSubject);\n    }\n\n    void injectByType(Set<Field> targetFields, Object testSubject) throws IllegalAccessException {\n        for (Field targetField : targetFields) {\n\n            InjectionTarget target = new InjectionTarget(targetField);\n\n            MockMetadata toAssign = findUniqueAssignable(target);\n\n            if (toAssign == null) {\n                continue;\n            }\n\n            target.inject(testSubject, toAssign);\n        }\n    }\n\n    MockMetadata findUniqueAssignable(InjectionTarget target) {\n        MockMetadata toAssign = null;\n        for (MockMetadata mockMetadata : globalMetadata.getUnqualifiedInjections()) {\n            if (target.accepts(mockMetadata)) {\n                if (toAssign != null) {\n                    throw new RuntimeException(String.format(\"At least two mocks can be assigned to '%s': %s and %s\", target.getField(), toAssign.getMock(), mockMetadata.getMock()));\n                }\n                toAssign = mockMetadata;\n            }\n        }\n        return toAssign;\n    }\n\n    Set<Field> injectByName(Set<Field> targetFields, Object targetObject) throws IllegalAccessException {\n        Class<?> targetClass = targetObject.getClass();\n\n        for (MockMetadata mockMetadata : globalMetadata.getQualifiedInjections()) {\n            Field targetField = getFieldByName(targetClass, mockMetadata.getQualifier());\n\n            if (targetField == null) {\n                continue;\n            }\n\n            InjectionTarget target = new InjectionTarget(targetField);\n\n            if (target.accepts(mockMetadata)) {\n                target.inject(targetObject, mockMetadata);\n                targetFields.remove(targetField);\n            }\n        }\n\n        return targetFields;\n    }\n\n    private Field getFieldByName(Class<?> clazz, String fieldName) {\n        try {\n            return clazz.getDeclaredField(fieldName);\n        } catch (NoSuchFieldException e) {\n            return null;\n        } catch (SecurityException e) {\n            return null;\n        }\n    }\n\n    private static class InjectionTarget {\n\n        private final Field field;\n\n        public InjectionTarget(Field field) {\n\n            this.field = field;\n        }\n\n        public Field getField() {\n            return field;\n        }\n\n        public boolean accepts(MockMetadata mockMetadata) {\n            return field.getType().isAssignableFrom(mockMetadata.getType());\n        }\n\n        public void inject(Object targetObject, MockMetadata mockMetadata) throws IllegalAccessException {\n            field.setAccessible(true);\n\n            Object value = field.get(targetObject);\n\n            if (value == null) {\n                field.set(targetObject, mockMetadata.getMock());\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/agent/JavaAgentFrameworkRegisterImpl.java",
    "content": "package org.powermock.api.extension.agent;\n\nimport org.powermock.api.mockito.internal.mockcreation.MockCreator;\nimport org.powermock.core.agent.JavaAgentClassRegister;\nimport org.powermock.core.agent.JavaAgentFrameworkRegister;\nimport org.powermock.reflect.Whitebox;\n\n/**\n * Implementation of JavaAgentFrameworkRegister for Mockito framework.\n */\npublic class JavaAgentFrameworkRegisterImpl implements JavaAgentFrameworkRegister {\n\n    public static final String MOCK_CREATOR_IMPLEMENTATION_CLASS = \"org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator\";\n\n    private MockCreator mockCreator;\n\n    @Override\n    public void set(JavaAgentClassRegister javaAgentClassRegister) {\n        setToPowerMockito(javaAgentClassRegister);\n    }\n\n    private void setToPowerMockito(JavaAgentClassRegister javaAgentClassRegister) {\n\n        mockCreator = getPowerMockCoreForCurrentClassLoader();\n        Whitebox.setInternalState(mockCreator, \"agentClassRegister\", javaAgentClassRegister);\n\n    }\n\n    private MockCreator getPowerMockCoreForCurrentClassLoader() {\n        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n        try {\n            return Whitebox.getInternalState(classLoader.loadClass(MOCK_CREATOR_IMPLEMENTATION_CLASS), \"MOCK_CREATOR\");\n        } catch (ClassNotFoundException e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n    @Override\n    public void clear() {\n        if (mockCreator == null) {\n            throw new IllegalStateException(\"Cannot clear JavaAgentClassRegister. Set method has not been called.\");\n        }\n        Whitebox.setInternalState(mockCreator, \"agentClassRegister\", (Object) null);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.extension.listener;\n\nimport org.mockito.Answers;\nimport org.mockito.ArgumentCaptor;\nimport org.mockito.Captor;\nimport org.mockito.Mock;\nimport org.mockito.MockSettings;\nimport org.mockito.exceptions.base.MockitoException;\nimport org.mockito.internal.configuration.InjectingAnnotationEngine;\nimport org.mockito.internal.util.reflection.GenericMaster;\nimport org.powermock.api.mockito.internal.configuration.PowerMockitoInjectingAnnotationEngine;\nimport org.powermock.core.spi.listener.AnnotationEnablerListener;\nimport org.powermock.core.spi.support.AbstractPowerMockTestListenerBase;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\nimport static org.mockito.Mockito.withSettings;\nimport static org.powermock.api.mockito.PowerMockito.mock;\n\n/**\n * Before each test method all fields annotated with {@link Mock},\n * {@link org.mockito.Mock} or {@link Mock} have mock objects created for them\n * and injected to the fields. It will also delegate to a special implementation\n * of the {@link InjectingAnnotationEngine} in Mockito which inject's spies,\n * captors etc.\n * <p/>\n * It will only inject to fields that haven't been set before (i.e that are\n * {@code null}).\n */\n@SuppressWarnings(\"deprecation\")\npublic class AnnotationEnabler extends AbstractPowerMockTestListenerBase implements AnnotationEnablerListener {\n\n    @Override\n    public void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception {\n        standardInject(testInstance);\n        injectSpiesAndInjectToSetters(testInstance);\n        injectCaptor(testInstance);\n    }\n\n    private void injectSpiesAndInjectToSetters(Object testInstance) {\n        new PowerMockitoInjectingAnnotationEngine().process(testInstance.getClass(), testInstance);\n    }\n\n    private void injectCaptor(Object testInstance) throws Exception {\n        Set<Field> fieldsAnnotatedWithCaptor = Whitebox.getFieldsAnnotatedWith(testInstance, Captor.class);\n        for (Field field : fieldsAnnotatedWithCaptor) {\n            final Object captor = processAnnotationOn(field.getAnnotation(Captor.class), field);\n            field.set(testInstance, captor);\n        }\n    }\n\n    private void standardInject(Object testInstance) throws IllegalAccessException {\n        Set<Field> fields = Whitebox.getFieldsAnnotatedWith(testInstance, getMockAnnotations());\n        for (Field field : fields) {\n            if (field.get(testInstance) != null) {\n                continue;\n            }\n            final Class<?> type = field.getType();\n\n            if (field.isAnnotationPresent(org.mockito.Mock.class)) {\n                org.mockito.Mock mockAnnotation = field.getAnnotation(org.mockito.Mock.class);\n                MockSettings mockSettings = withSettings();\n                Answers answers = mockAnnotation.answer();\n                if (answers != null) {\n                    mockSettings.defaultAnswer(answers);\n                }\n\n                Class<?>[] extraInterfaces = mockAnnotation.extraInterfaces();\n                if (extraInterfaces != null && extraInterfaces.length > 0) {\n                    mockSettings.extraInterfaces(extraInterfaces);\n                }\n\n                String name = mockAnnotation.name();\n                if (name != null && name.length() > 0) {\n                    mockSettings.name(name);\n                }\n\n                field.set(testInstance, mock(type, mockSettings));\n            } else {\n                field.set(testInstance, mock(type));\n            }\n        }\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    public Class<? extends Annotation>[] getMockAnnotations() {\n        return new Class[]{org.mockito.Mock.class, Mock.class};\n    }\n\n    private Object processAnnotationOn(Captor annotation, Field field) {\n        Class<?> type = field.getType();\n        if (!ArgumentCaptor.class.isAssignableFrom(type)) {\n            throw new MockitoException(\"@Captor field must be of the type ArgumentCaptor.\\n\" + \"Field: '\"\n                    + field.getName() + \"' has wrong type\\n\"\n                    + \"For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class.\");\n        }\n        Class cls = new GenericMaster().getGenericType(field);\n        return ArgumentCaptor.forClass(cls);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/ClassNotPreparedException.java",
    "content": "package org.powermock.api.mockito;\n\n/**\n * The exception is thrown when a user tries to mock class which is't prepared, but should be. For example it could\n * be case mocking static call.\n */\npublic class ClassNotPreparedException extends RuntimeException {\n\n    public ClassNotPreparedException(String message) {\n        super(message);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito;\n\nimport org.mockito.MockSettings;\nimport org.mockito.Mockito;\nimport org.mockito.stubbing.Answer;\nimport org.mockito.stubbing.OngoingStubbing;\nimport org.mockito.verification.VerificationMode;\nimport org.powermock.api.mockito.expectation.ConstructorAwareExpectationSetup;\nimport org.powermock.api.mockito.expectation.ConstructorExpectationSetup;\nimport org.powermock.api.mockito.expectation.DefaultConstructorExpectationSetup;\nimport org.powermock.api.mockito.expectation.PowerMockitoStubber;\nimport org.powermock.api.mockito.expectation.WithOrWithoutExpectedArguments;\nimport org.powermock.api.mockito.internal.PowerMockitoCore;\nimport org.powermock.api.mockito.internal.expectation.DefaultMethodExpectationSetup;\nimport org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator;\nimport org.powermock.api.mockito.internal.verification.DefaultPrivateMethodVerification;\nimport org.powermock.api.mockito.internal.verification.VerifyNoMoreInteractions;\nimport org.powermock.api.mockito.verification.ConstructorArgumentsVerification;\nimport org.powermock.api.mockito.verification.PrivateMethodVerification;\nimport org.powermock.api.support.membermodification.MemberModifier;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\n\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.withSettings;\n\n/**\n * PowerMockito extends Mockito functionality with several new features such as\n * mocking static and private methods and more. Use PowerMock instead of Mockito\n * where applicable.\n *\n * @see Mockito\n */\npublic class PowerMockito extends MemberModifier {\n    \n    private static final PowerMockitoCore POWERMOCKITO_CORE = new PowerMockitoCore();\n    \n    /**\n     * Enable static mocking for all methods of a class.\n     *\n     * @param type the class to enable static mocking\n     */\n    public static synchronized void mockStatic(Class<?> type, Class<?>... types) {\n        DefaultMockCreator.mock(type, true, false, null, null, (Method[]) null);\n        if (types != null && types.length > 0) {\n            for (Class<?> aClass : types) {\n                DefaultMockCreator.mock(aClass, true, false, null, null, (Method[]) null);\n            }\n        }\n    }\n    \n    /**\n     * Creates class mock with a specified strategy for its answers to\n     * interactions. It's quite advanced feature and typically you don't need it\n     * to write decent tests. However it can be helpful when working with legacy\n     * systems.\n     * <p>\n     * It is the default answer so it will be used <b>only when you don't</b>\n     * stub the method call.\n     * <p>\n     * <pre>\n     * mockStatic(Foo.class, RETURNS_SMART_NULLS);\n     * mockStatic(Foo.class, new YourOwnAnswer());\n     * </pre>\n     *\n     * @param classMock     class to mock\n     * @param defaultAnswer default answer for unstubbed methods\n     */\n    public static void mockStatic(Class<?> classMock, @SuppressWarnings(\"rawtypes\") Answer defaultAnswer) {\n        mockStatic(classMock, withSettings().defaultAnswer(defaultAnswer));\n    }\n    \n    /**\n     * Creates a class mock with some non-standard settings.\n     * <p>\n     * The number of configuration points for a mock grows so we need a fluent\n     * way to introduce new configuration without adding more and more\n     * overloaded PowerMockito.mockStatic() methods. Hence {@link MockSettings}.\n     * <p>\n     * <pre>\n     *   mockStatic(Listener.class, withSettings()\n     *     .name(&quot;firstListner&quot;).defaultBehavior(RETURNS_SMART_NULLS));\n     *   );\n     * </pre>\n     * <p>\n     * <b>Use it carefully and occasionally</b>. What might be reason your test\n     * needs non-standard mocks? Is the code under test so complicated that it\n     * requires non-standard mocks? Wouldn't you prefer to refactor the code\n     * under test so it is testable in a simple way?\n     * <p>\n     * See also {@link Mockito#withSettings()}\n     *\n     * @param classToMock  class to mock\n     * @param mockSettings additional mock settings\n     */\n    public static void mockStatic(Class<?> classToMock, MockSettings mockSettings) {\n        DefaultMockCreator.mock(classToMock, true, false, null, mockSettings, (Method[]) null);\n    }\n    \n    /**\n     * Creates a mock object that supports mocking of final and native methods.\n     *\n     * @param <T>  the type of the mock object\n     * @param type the type of the mock object\n     * @return the mock object.\n     */\n    public static synchronized <T> T mock(Class<T> type) {\n        return DefaultMockCreator.mock(type, false, false, null, null, (Method[]) null);\n    }\n    \n    /**\n     * Creates mock with a specified strategy for its answers to interactions.\n     * It's quite advanced feature and typically you don't need it to write\n     * decent tests. However it can be helpful when working with legacy systems.\n     * <p>\n     * It is the default answer so it will be used <b>only when you don't</b>\n     * stub the method call.\n     * <p>\n     * <pre>\n     * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);\n     * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());\n     * </pre>\n     * <p>\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     * </p>\n     *\n     * @param classToMock   class or interface to mock\n     * @param defaultAnswer default answer for unstubbed methods\n     * @return mock object\n     */\n    public static <T> T mock(Class<T> classToMock, @SuppressWarnings(\"rawtypes\") Answer defaultAnswer) {\n        return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));\n    }\n    \n    /**\n     * Creates a mock with some non-standard settings.\n     * <p>\n     * The number of configuration points for a mock grows so we need a fluent\n     * way to introduce new configuration without adding more and more\n     * overloaded Mockito.mock() methods. Hence {@link MockSettings}.\n     * <p>\n     * <pre>\n     *   Listener mock = mock(Listener.class, withSettings()\n     *     .name(&quot;firstListner&quot;).defaultBehavior(RETURNS_SMART_NULLS));\n     *   );\n     * </pre>\n     * <p>\n     * <b>Use it carefully and occasionally</b>. What might be reason your test\n     * needs non-standard mocks? Is the code under test so complicated that it\n     * requires non-standard mocks? Wouldn't you prefer to refactor the code\n     * under test so it is testable in a simple way?\n     * <p>\n     * See also {@link Mockito#withSettings()}\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     *\n     * @param classToMock  class or interface to mock\n     * @param mockSettings additional mock settings\n     * @return mock object\n     */\n    public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {\n        return DefaultMockCreator.mock(classToMock, false, false, null, mockSettings, (Method[]) null);\n    }\n    \n    /**\n     * Spy on objects that are final or otherwise not &quot;spyable&quot; from\n     * normal Mockito.\n     *\n     * @param <T>    the type of the mock object\n     * @param object the object to spy on\n     * @return the spy object.\n     * @see PowerMockito#spy(Object)\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T spy(T object) {\n        return POWERMOCKITO_CORE.spy(object);\n    }\n    \n    /**\n     * Spy on classes (not &quot;spyable&quot; from normal Mockito).\n     *\n     * @param <T>  the type of the class mock\n     * @param type the type of the class mock\n     * @see PowerMockito#spy(Object)\n     */\n    public static synchronized <T> void spy(Class<T> type) {\n        MockSettings mockSettings = Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS);\n        DefaultMockCreator.mock(type, true, true, type, mockSettings, (Method[]) null);\n    }\n    \n    /**\n     * Verifies certain behavior of the <code>mockedClass</code> <b>happened once</b>\n     * <p>\n     * Alias to {@code verifyStatic(classMock, times(1))} E.g:\n     * <p>\n     * <pre>\n     * verifyStatic(ClassWithStaticMethod.class);\n     * ClassWithStaticMethod.someStaticMethod(&quot;some arg&quot;);\n     * </pre>\n     * <p>\n     * Above is equivalent to:\n     * <p>\n     * <pre>\n     * verifyStatic(ClassWithStaticMethod.class, times(1));\n     * ClassWithStaticMethod.someStaticMethod(&quot;some arg&quot;);\n     * </pre>\n     * <p>\n     * <p>\n     * Although it is possible to verify a stubbed invocation, usually <b>it's\n     * just redundant</b>. Let's say you've stubbed foo.bar(). If your code\n     * cares what foo.bar() returns then something else breaks(often before even\n     * verify() gets executed). If your code doesn't care what get(0) returns\n     * then it should not be stubbed.\n     *\n     * @param mockedClass the mocked class behavior of that have to be verified.\n     */\n    public static synchronized <T> void verifyStatic(Class<T> mockedClass) {\n        verifyStatic(mockedClass, times(1));\n    }\n    \n    /**\n     * Verifies certain behavior of the <code>mockedClass</code> happened at least once / exact number of times\n     * / never. E.g:\n     * <p>\n     * <pre>\n     *   verifyStatic(ClassWithStaticMethod.class, times(5));\n     *   ClassWithStaticMethod.someStaticMethod(&quot;was called five times&quot;);\n     *\n     *   verifyStatic(ClassWithStaticMethod.class, atLeast(2));\n     *   ClassWithStaticMethod.someStaticMethod(&quot;was called at least two times&quot;);\n     *\n     *   //you can use flexible argument matchers, e.g:\n     *   verifyStatic(ClassWithStaticMethod.class, atLeastOnce());\n     *   ClassWithStaticMethod.someMethod(&lt;b&gt;anyString()&lt;/b&gt;);\n     * </pre>\n     * <p>\n     * <b>times(1) is the default</b> and can be omitted\n     * <p>\n     *\n     * @param mockedClass      the mocked class behavior of that have to be verified.\n     * @param verificationMode times(x), atLeastOnce() or never()\n     */\n    public static synchronized <T> void verifyStatic(Class<T> mockedClass, VerificationMode verificationMode) {\n        Mockito.verify(mockedClass, verificationMode);\n    }\n    \n    /**\n     * Verify a private method invocation for an instance.\n     *\n     * @see Mockito#verify(Object)\n     */\n    public static PrivateMethodVerification verifyPrivate(Object object) {\n        return verifyPrivate(object, times(1));\n    }\n    \n    /**\n     * Verify a private method invocation with a given verification mode.\n     *\n     * @see Mockito#verify(Object)\n     */\n    public static PrivateMethodVerification verifyPrivate(Object object, VerificationMode verificationMode) {\n        Mockito.verify(object, verificationMode);\n        return new DefaultPrivateMethodVerification(object);\n    }\n    \n    /**\n     * Verify a private method invocation for a class.\n     *\n     * @throws Exception If something unexpected goes wrong.\n     * @see Mockito#verify(Object)\n     */\n    public static PrivateMethodVerification verifyPrivate(Class<?> clazz) throws Exception {\n        return verifyPrivate((Object) clazz);\n    }\n    \n    /**\n     * Verify a private method invocation for a class with a given verification\n     * mode.\n     *\n     * @see Mockito#verify(Object)\n     */\n    public static PrivateMethodVerification verifyPrivate(Class<?> clazz, VerificationMode verificationMode) {\n        return verifyPrivate((Object) clazz, verificationMode);\n    }\n    \n    /**\n     * Verifies certain behavior <b>happened once</b>\n     * <p>\n     * Alias to <code>verifyNew(mockClass, times(1))</code> E.g:\n     * <p>\n     * <pre>\n     * verifyNew(ClassWithStaticMethod.class);\n     * </pre>\n     * <p>\n     * Above is equivalent to:\n     * <p>\n     * <pre>\n     * verifyNew(ClassWithStaticMethod.class, times(1));\n     * </pre>\n     * <p>\n     * <p>\n     *\n     * @param mock Class mocked by PowerMock.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> ConstructorArgumentsVerification verifyNew(Class<T> mock) {\n        return verifyNew(mock, times(1));\n    }\n    \n    /**\n     * Verifies certain behavior happened at least once / exact number of times\n     * / never. E.g:\n     * <p>\n     * <pre>\n     * verifyNew(ClassWithStaticMethod.class, times(5));\n     *\n     * verifyNew(ClassWithStaticMethod.class, atLeast(2));\n     *\n     * //you can use flexible argument matchers, e.g:\n     * verifyNew(ClassWithStaticMethod.class, atLeastOnce());\n     * </pre>\n     * <p>\n     * <b>times(1) is the default</b> and can be omitted\n     * <p>\n     *\n     * @param mock to be verified\n     * @param mode times(x), atLeastOnce() or never()\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> ConstructorArgumentsVerification verifyNew(Class<T> mock, VerificationMode mode) {\n       return  POWERMOCKITO_CORE.verifyNew(mock, mode);\n    }\n    \n    /**\n     * Expect calls to private methods.\n     *\n     * @throws Exception If something unexpected goes wrong.\n     * @see PowerMockito#when(Object)\n     */\n    public static <T> OngoingStubbing<T> when(Object instance, String methodName, Object... arguments) throws Exception {\n        return Mockito.when(Whitebox.<T>invokeMethod(instance, methodName, arguments));\n    }\n    \n    /**\n     * Expect calls to private methods.\n     *\n     * @see PowerMockito#when(Object)\n     */\n    public static <T> WithOrWithoutExpectedArguments<T> when(Object instance, Method method) {\n        return new DefaultMethodExpectationSetup<T>(instance, method);\n    }\n    \n    /**\n     * Expect calls to private static methods.\n     *\n     * @see PowerMockito#when(Object)\n     */\n    public static <T> WithOrWithoutExpectedArguments<T> when(Class<?> cls, Method method) {\n        return new DefaultMethodExpectationSetup<T>(cls, method);\n    }\n    \n    /**\n     * Expect calls to private methods without having to specify the method\n     * name. The method will be looked up using the parameter types (if\n     * possible).\n     *\n     * @throws Exception If something unexpected goes wrong.\n     * @see PowerMockito#when(Object)\n     */\n    public static <T> OngoingStubbing<T> when(Object instance, Object... arguments) throws Exception {\n        return Mockito.when(Whitebox.<T>invokeMethod(instance, arguments));\n    }\n    \n    /**\n     * Expect a static private or inner class method call.\n     *\n     * @throws Exception If something unexpected goes wrong.\n     * @see PowerMockito#when(Object)\n     */\n    public static <T> OngoingStubbing<T> when(Class<?> clazz, String methodToExpect, Object... arguments)\n        throws Exception {\n        return Mockito.when(Whitebox.<T>invokeMethod(clazz, methodToExpect, arguments));\n    }\n    \n    /**\n     * Expect calls to private static methods without having to specify the\n     * method name. The method will be looked up using the parameter types if\n     * possible\n     *\n     * @throws Exception If something unexpected goes wrong.\n     * @see PowerMockito#when(Object)\n     */\n    public static <T> OngoingStubbing<T> when(Class<?> klass, Object... arguments) throws Exception {\n        return Mockito.when(Whitebox.<T>invokeMethod(klass, arguments));\n    }\n    \n    /**\n     * Just delegates to the original {@link Mockito#when(Object)} method.\n     *\n     * @see PowerMockito#when(Object)\n     */\n    public static <T> OngoingStubbing<T> when(T methodCall) {\n        return Mockito.when(methodCall);\n    }\n    \n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock.\n     */\n    public static synchronized <T> WithOrWithoutExpectedArguments<T> whenNew(Constructor<T> ctor) {\n        return new ConstructorAwareExpectationSetup<T>(ctor);\n    }\n    \n    /**\n     * Allows specifying expectations on new invocations. For example you might\n     * want to throw an exception or return a mock.\n     */\n    public static synchronized <T> ConstructorExpectationSetup<T> whenNew(Class<T> type) {\n        return new DefaultConstructorExpectationSetup<T>(type);\n    }\n    \n    /**\n     * Allows specifying expectations on new invocations for private member\n     * (inner) classes, local or anonymous classes. For example you might want\n     * to throw an exception or return a mock.\n     *\n     * @param fullyQualifiedName The fully-qualified name of the inner/local/anonymous type to\n     *                           expect.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> ConstructorExpectationSetup<T> whenNew(String fullyQualifiedName) throws Exception {\n        final Class<T> forName = (Class<T>) Class.forName(fullyQualifiedName);\n        return new DefaultConstructorExpectationSetup<T>(forName);\n    }\n    \n    /**\n     * Checks if any of given mocks (can be both instance and class mocks) has\n     * any unverified interaction. Delegates to the original\n     * {@link Mockito#verifyNoMoreInteractions(Object...)} if the mock is not a\n     * PowerMockito mock.\n     * <p>\n     * You can use this method after you verified your mocks - to make sure that\n     * nothing else was invoked on your mocks.\n     * <p>\n     * See also {@link Mockito#never()} - it is more explicit and communicates\n     * the intent well.\n     * <p>\n     * Stubbed invocations (if called) are also treated as interactions.\n     * <p>\n     * A word of <b>warning</b>: Some users who did a lot of classic,\n     * expect-run-verify mocking tend to use verifyNoMoreInteractions() very\n     * often, even in every test method. verifyNoMoreInteractions() is not\n     * recommended to use in every test method. verifyNoMoreInteractions() is a\n     * handy assertion from the interaction testing toolkit. Use it only when\n     * it's relevant. Abusing it leads to over-specified, less maintainable\n     * tests. You can find further reading <a href=\n     * \"http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/\"\n     * >here</a>.\n     * <p>\n     * This method will also detect unverified invocations that occurred before\n     * the test method, for example: in setUp(), &#064;Before method or in\n     * constructor. Consider writing nice code that makes interactions only in\n     * test methods.\n     * <p>\n     * <p>\n     * Example:\n     * <p>\n     * <pre>\n     * //interactions\n     * mock.doSomething();\n     * mock.doSomethingUnexpected();\n     *\n     * //verification\n     * verify(mock).doSomething();\n     *\n     * //following will fail because 'doSomethingUnexpected()' is unexpected\n     * verifyNoMoreInteractions(mock);\n     *\n     * </pre>\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     *\n     * @param mocks to be verified\n     */\n    public static void verifyNoMoreInteractions(Object... mocks) {\n        VerifyNoMoreInteractions.verifyNoMoreInteractions(mocks);\n    }\n    \n    /**\n     * Verifies that no interactions happened on given mocks (can be both\n     * instance and class mocks). Delegates to the original\n     * {@link PowerMockito#verifyNoMoreInteractions(Object...)} if the mock is not a\n     * PowerMockito mock.\n     * <p>\n     * <pre>\n     * verifyZeroInteractions(mockOne, mockTwo);\n     * </pre>\n     * <p>\n     * This method will also detect invocations that occurred before the test\n     * method, for example: in setUp(), &#064;Before method or in constructor.\n     * Consider writing nice code that makes interactions only in test methods.\n     * <p>\n     * See also {@link Mockito#never()} - it is more explicit and communicates\n     * the intent well.\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     *\n     * @param mocks to be verified\n     */\n    public static void verifyZeroInteractions(Object... mocks) {\n        VerifyNoMoreInteractions.verifyNoMoreInteractions(mocks);\n    }\n    \n    /**\n     * Use doAnswer() when you want to stub a void method with generic\n     * {@link Answer}.\n     * <p>\n     * Stubbing voids requires different approach from\n     * {@link PowerMockito#when(Object)} because the compiler does not like void\n     * methods inside brackets...\n     * <p>\n     * Example:\n     * <p>\n     * <pre>\n     * doAnswer(new Answer() {\n     *     public Object answer(InvocationOnMock invocation) {\n     *         Object[] args = invocation.getArguments();\n     *         Mock mock = invocation.getMock();\n     *         return null;\n     *     }\n     * }).when(mock).someMethod();\n     * </pre>\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     *\n     * @param answer to answer when the stubbed method is called\n     * @return stubber - to select a method for stubbing\n     */\n    public static PowerMockitoStubber doAnswer(Answer<?> answer) {\n        return POWERMOCKITO_CORE.doAnswer(answer);\n    }\n    \n    /**\n     * Use doThrow() when you want to stub the void method with an exception.\n     * <p>\n     * Stubbing voids requires different approach from\n     * {@link PowerMockito#when(Object)} because the compiler does not like void\n     * methods inside brackets...\n     * <p>\n     * Example:\n     * <p>\n     * <pre>\n     * doThrow(new RuntimeException()).when(mock).someVoidMethod();\n     * </pre>\n     *\n     * @param toBeThrown to be thrown when the stubbed method is called\n     * @return stubber - to select a method for stubbing\n     */\n    public static PowerMockitoStubber doThrow(Throwable toBeThrown) {\n        return POWERMOCKITO_CORE.doThrow(toBeThrown);\n    }\n    \n    /**\n     * Use doCallRealMethod() when you want to call the real implementation of a\n     * method.\n     * <p>\n     * As usual you are going to read <b>the partial mock warning</b>: Object\n     * oriented programming is more less tackling complexity by dividing the\n     * complexity into separate, specific, SRPy objects. How does partial mock\n     * fit into this paradigm? Well, it just doesn't... Partial mock usually\n     * means that the complexity has been moved to a different method on the\n     * same object. In most cases, this is not the way you want to design your\n     * application.\n     * <p>\n     * However, there are rare cases when partial mocks come handy: dealing with\n     * code you cannot change easily (3rd party interfaces, interim refactoring\n     * of legacy code etc.) However, I wouldn't use partial mocks for new,\n     * test-driven & well-designed code.\n     * <p>\n     * See also javadoc {@link PowerMockito#spy(Object)} to find out more about\n     * partial mocks. <b>Mockito.spy() is a recommended way of creating partial\n     * mocks.</b> The reason is it guarantees real methods are called against\n     * correctly constructed object because you're responsible for constructing\n     * the object passed to spy() method.\n     * <p>\n     * Example:\n     * <p>\n     * <pre>\n     * Foo mock = mock(Foo.class);\n     * doCallRealMethod().when(mock).someVoidMethod();\n     *\n     * // this will call the real implementation of Foo.someVoidMethod()\n     * mock.someVoidMethod();\n     * </pre>\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     *\n     * @return stubber - to select a method for stubbing\n     */\n    public static PowerMockitoStubber doCallRealMethod() {\n        return POWERMOCKITO_CORE.doCallRealMethod();\n    }\n    \n    /**\n     * Use doNothing() for setting void methods to do nothing. <b>Beware that\n     * void methods on mocks do nothing by default!</b> However, there are rare\n     * situations when doNothing() comes handy:\n     * <p>\n     * 1. Stubbing consecutive calls on a void method:\n     * <p>\n     * <pre>\n     * doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod();\n     *\n     * //does nothing the first time:\n     * mock.someVoidMethod();\n     *\n     * //throws RuntimeException the next time:\n     * mock.someVoidMethod();\n     * </pre>\n     * <p>\n     * 2. When you spy real objects and you want the void method to do nothing:\n     * <p>\n     * <pre>\n     * List list = new LinkedList();\n     * List spy = spy(list);\n     *\n     * //let's make clear() do nothing\n     * doNothing().when(spy).clear();\n     *\n     * spy.add(&quot;one&quot;);\n     *\n     * //clear() does nothing, so the list still contains &quot;one&quot;\n     * spy.clear();\n     * </pre>\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     *\n     * @return stubber - to select a method for stubbing\n     */\n    public static PowerMockitoStubber doNothing() {\n        return POWERMOCKITO_CORE.doNothing();\n    }\n    \n    /**\n     * Use doReturn() in those rare occasions when you cannot use\n     * {@link PowerMockito#when(Object)}.\n     * <p>\n     * <b>Beware that {@link PowerMockito#when(Object)} is always recommended for\n     * stubbing because it is argument type-safe and more readable</b>\n     * (especially when stubbing consecutive calls).\n     * <p>\n     * Here are those rare occasions when doReturn() comes handy:\n     * <p>\n     * <p>\n     * 1. When spying real objects and calling real methods on a spy brings side\n     * effects\n     * <p>\n     * <pre>\n     * List list = new LinkedList();\n     * List spy = spy(list);\n     *\n     * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)\n     * when(spy.get(0)).thenReturn(&quot;foo&quot;);\n     *\n     * //You have to use doReturn() for stubbing:\n     * doReturn(&quot;foo&quot;).when(spy).get(0);\n     * </pre>\n     * <p>\n     * 2. Overriding a previous exception-stubbing:\n     * <p>\n     * <pre>\n     * when(mock.foo()).thenThrow(new RuntimeException());\n     *\n     * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.\n     * when(mock.foo()).thenReturn(&quot;bar&quot;);\n     *\n     * //You have to use doReturn() for stubbing:\n     * doReturn(&quot;bar&quot;).when(mock).foo();\n     * </pre>\n     * <p>\n     * Above scenarios shows a trade off of Mockito's elegant syntax. Note that\n     * the scenarios are very rare, though. Spying should be sporadic and\n     * overriding exception-stubbing is very rare.\n     * <p>\n     * See examples in javadoc for {@link Mockito} class\n     *\n     * @param toBeReturned to be returned when the stubbed method is called\n     * @return stubber - to select a method for stubbing\n     */\n    public static PowerMockitoStubber doReturn(Object toBeReturned) {\n        return POWERMOCKITO_CORE.doReturn(toBeReturned);\n    }\n    \n    \n    /**\n     * Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use\n     * <code>doReturn()</code> in those rare occasions when you cannot use {@link PowerMockito#when(Object)}.\n     * <p>\n     * <b>Beware that {@link PowerMockito#when(Object)} is always recommended for stubbing because it is argument type-safe\n     * and more readable</b> (especially when stubbing consecutive calls).\n     * <p>\n     * Here are those rare occasions when doReturn() comes handy:\n     * <p>\n     * <p>\n     * <ol>\n     * <li>When spying real objects and calling real methods on a spy brings side effects\n     * <p>\n     * <pre class=\"code\"><code class=\"java\">\n     * List list = new LinkedList();\n     * List spy = spy(list);\n     * <p>\n     * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)\n     * when(spy.get(0)).thenReturn(\"foo\", \"bar\", \"qix\");\n     * <p>\n     * //You have to use doReturn() for stubbing:\n     * doReturn(\"foo\", \"bar\", \"qix\").when(spy).get(0);\n     * </code></pre>\n     * </li>\n     * <p>\n     * <li>Overriding a previous exception-stubbing:\n     * <pre class=\"code\"><code class=\"java\">\n     * when(mock.foo()).thenThrow(new RuntimeException());\n     * <p>\n     * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.\n     * when(mock.foo()).thenReturn(\"bar\", \"foo\", \"qix\");\n     * <p>\n     * //You have to use doReturn() for stubbing:\n     * doReturn(\"bar\", \"foo\", \"qix\").when(mock).foo();\n     * </code></pre>\n     * </li>\n     * </ol>\n     * <p>\n     * Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.\n     * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general\n     * overriding stubbing is a potential code smell that points out too much stubbing.\n     * <p>\n     * See examples in javadoc for {@link PowerMockito} class\n     *\n     * @param toBeReturned       to be returned when the stubbed method is called\n     * @param othersToBeReturned to be returned in consecutive calls when the stubbed method is called\n     * @return stubber - to select a method for stubbing\n     * @since 1.6.5\n     */\n    public static PowerMockitoStubber doReturn(Object toBeReturned, Object... othersToBeReturned) {\n        return POWERMOCKITO_CORE.doAnswer(toBeReturned, othersToBeReturned);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorAwareExpectationSetup.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.expectation;\n\nimport org.mockito.stubbing.OngoingStubbing;\n\nimport java.lang.reflect.Constructor;\n\npublic class ConstructorAwareExpectationSetup<T> implements WithOrWithoutExpectedArguments<T> {\n    \n    private final Constructor<T> ctor;\n    private final DefaultConstructorExpectationSetup<T> expectationSetup;\n    \n    public ConstructorAwareExpectationSetup(Constructor<T> ctor) {\n        if (ctor == null) {\n            throw new IllegalArgumentException(\"Constructor to expect cannot be null\");\n        }\n        this.ctor = ctor;\n        this.expectationSetup = setupExpectation();\n    }\n    \n    @Override\n    public OngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception {\n        return expectationSetup.withArguments(firstArgument, additionalArguments);\n    }\n    \n    @Override\n    public OngoingStubbing<T> withNoArguments() throws Exception {\n        return expectationSetup.withNoArguments();\n    }\n    \n    private DefaultConstructorExpectationSetup<T> setupExpectation() {\n        DefaultConstructorExpectationSetup<T> setup = new DefaultConstructorExpectationSetup<T>(ctor.getDeclaringClass());\n        setup.setParameterTypes(ctor.getParameterTypes());\n        return setup;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorExpectationSetup.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.expectation;\n\npublic interface ConstructorExpectationSetup<T> extends WithOrWithoutExpectedArguments<T>, WithExpectedParameterTypes<T>, WithAnyArguments<T> {\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/DefaultConstructorExpectationSetup.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.expectation;\n\nimport org.mockito.ArgumentMatchers;\nimport org.mockito.stubbing.OngoingStubbing;\nimport org.powermock.api.mockito.internal.expectation.DelegatingToConstructorsOngoingStubbing;\nimport org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl;\nimport org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator;\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.spi.NewInvocationControl;\nimport org.powermock.core.spi.support.InvocationSubstitute;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport org.powermock.tests.utils.ArrayMerger;\nimport org.powermock.tests.utils.impl.ArrayMergerImpl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\n\npublic class DefaultConstructorExpectationSetup<T> implements ConstructorExpectationSetup<T> {\n    \n    private final Class<T> mockType;\n    private final ArrayMerger arrayMerger;\n    private final DefaultMockCreator mockCreator;\n    private Class<?>[] parameterTypes = null;\n    private final InvocationSubstitute mock;\n    \n    public DefaultConstructorExpectationSetup(Class<T> mockType) {\n        this.arrayMerger = new ArrayMergerImpl();\n        this.mockType = mockType;\n        this.mockCreator = new DefaultMockCreator();\n        this.mock = getMockCreator().createMock(InvocationSubstitute.class, false, false, null, null, (Method[]) null);\n    }\n    \n    @Override\n    public OngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception {\n        return createNewSubstituteMock(mockType, parameterTypes, arrayMerger.mergeArrays(Object.class, new Object[]{firstArgument},\n                                                                                         additionalArguments));\n    }\n    \n    @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n    private OngoingStubbing<T> createNewSubstituteMock(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception {\n        if (type == null) {\n            throw new IllegalArgumentException(\"type cannot be null\");\n        }\n        \n        final Class<T> unmockedType = (Class<T>) WhiteboxImpl.getOriginalUnmockedType(type);\n        if (parameterTypes == null) {\n            WhiteboxImpl.findUniqueConstructorOrThrowException(type, arguments);\n        } else {\n            WhiteboxImpl.getConstructor(unmockedType, parameterTypes);\n        }\n        \n        NewInvocationControl<OngoingStubbing<T>> newInvocationControl = createNewInvocationControl(type, unmockedType);\n        \n        return newInvocationControl.expectSubstitutionLogic(arguments);\n    }\n    \n    private NewInvocationControl<OngoingStubbing<T>> createNewInvocationControl(final Class<T> type, final Class<T> unmockedType) {\n        /*\n        * Check if this type has been mocked before\n        */\n        NewInvocationControl<OngoingStubbing<T>> newInvocationControl =\n            (NewInvocationControl<OngoingStubbing<T>>) MockRepository.getNewInstanceControl(unmockedType);\n        if (newInvocationControl == null) {\n            newInvocationControl = createNewInvocationControl(mock);\n            MockRepository.putNewInstanceControl(type, newInvocationControl);\n            MockRepository.addObjectsToAutomaticallyReplayAndVerify(WhiteboxImpl.getOriginalUnmockedType(type));\n        }\n        return newInvocationControl;\n    }\n    \n    @Override\n    public OngoingStubbing<T> withAnyArguments() throws Exception {\n        if (mockType == null) {\n            throw new IllegalArgumentException(\"Class to expected cannot be null\");\n        }\n        final Class<T> unmockedType = (Class<T>) WhiteboxImpl.getOriginalUnmockedType(mockType);\n        final Constructor<?>[] allConstructors = WhiteboxImpl.getAllConstructors(unmockedType);\n        final Constructor<?> constructor = allConstructors[0];\n        final Class<?>[] parameterTypes = constructor.getParameterTypes();\n        Object[] paramArgs = new Object[parameterTypes.length];\n        for (int i = 0; i < parameterTypes.length; i++) {\n            Class<?> paramType = parameterTypes[i];\n            paramArgs[i] = createParamArgMatcher(paramType);\n        }\n        Constructor<?>[] otherCtors = new Constructor<?>[allConstructors.length - 1];\n        System.arraycopy(allConstructors, 1, otherCtors, 0, allConstructors.length - 1);\n        \n        final OngoingStubbing<T> ongoingStubbing = createNewSubstituteMock(mockType, parameterTypes, paramArgs);\n        return new DelegatingToConstructorsOngoingStubbing<T>(otherCtors, ongoingStubbing);\n    }\n    \n    private Object createParamArgMatcher(Class<?> paramType) {\n        return ArgumentMatchers.nullable(paramType);\n    }\n    \n    @Override\n    public OngoingStubbing<T> withNoArguments() throws Exception {\n        return createNewSubstituteMock(mockType, parameterTypes);\n    }\n    \n    @Override\n    public WithExpectedArguments<T> withParameterTypes(Class<?> parameterType, Class<?>... additionalParameterTypes) {\n        this.parameterTypes = arrayMerger.mergeArrays(Class.class, new Class<?>[]{parameterType}, additionalParameterTypes);\n        return this;\n    }\n    \n    private DefaultMockCreator getMockCreator() {return mockCreator;}\n    \n    private NewInvocationControl<OngoingStubbing<T>> createNewInvocationControl(InvocationSubstitute<T> mock) {\n        return new MockitoNewInvocationControl<T>(mock);\n    }\n    \n    void setParameterTypes(Class<?>[] parameterTypes) {\n        this.parameterTypes = parameterTypes;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/PowerMockitoStubber.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.expectation;\n\nimport org.mockito.Mockito;\nimport org.mockito.stubbing.Answer;\nimport org.mockito.stubbing.Stubber;\n\nimport java.lang.reflect.Method;\n\n/**\n * Setup stubbing for private or void methods in final class, final void\n * methods, or static (final) methods.\n */\npublic interface PowerMockitoStubber extends Stubber {\n    \n    /**\n     * Allows to choose a static method when stubbing in\n     * doThrow()|doAnswer()|doNothing()|doReturn() style\n     * <p>\n     * Example:\n     * </p>\n     * <pre>\n     * doThrow(new RuntimeException()).when(StaticList.class);\n     * StaticList.clear();\n     *\n     * //following throws RuntimeException:\n     * StaticList.clear();\n     * </pre>\n     * <p>\n     * Read more about those methods:\n     * </p>\n     * <p>\n     * {@link Mockito#doThrow(Class)}\n     * </p>\n     * <p>\n     * {@link Mockito#doAnswer(Answer)}\n     * </p>\n     * <p>\n     * {@link Mockito#doNothing()}\n     * </p>\n     * <p>\n     * {@link Mockito#doReturn(Object)}\n     * </p>\n     *\n     * @param classMock the mock class\n     * @see Mockito\n     */\n    void when(Class<?> classMock);\n    \n    /**\n     * Allows to mock a private instance method when stubbing in\n     * doThrow()|doAnswer()|doNothing()|doReturn() style.\n     * <p>\n     * Example:\n     * <pre>\n     * doThrow(new RuntimeException()).when(instance, method(&quot;myMethod&quot;)).withNoArguments();\n     * </pre>\n     * </p>\n     * <p>\n     * Read more about those methods:\n     * </p>\n     * <p>\n     * {@link Mockito#doThrow(Class)}\n     * </p>\n     * <p>\n     * {@link Mockito#doAnswer(Answer)}\n     * </p>\n     * <p>\n     * {@link Mockito#doNothing()}\n     * </p>\n     * <p>\n     * {@link Mockito#doReturn(Object)}\n     * </p>\n     *\n     * @param mock   the method\n     * @param method private  method to be mocked\n     * @see Mockito\n     */\n    <T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception;\n    \n    /**\n     * Allows to mock a private instance method based on the parameters when\n     * stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style.\n     * <p>\n     * Example:\n     * </p>\n     * <p>\n     * <pre>\n     * doThrow(new RuntimeException()).when(instance, parameter1, parameter2);\n     * </pre>\n     * </p>\n     * <p>\n     * Read more about those methods:\n     * </p>\n     * <p>\n     * {@link Mockito#doThrow(Throwable...)}\n     * </p>\n     * <p>\n     * {@link Mockito#doAnswer(Answer)}\n     * </p>\n     * <p>\n     * {@link Mockito#doNothing()}\n     * </p>\n     * <p>\n     * {@link Mockito#doReturn(Object)}\n     * </p>\n     *\n     * @param mock      the Mock\n     * @param arguments array of arguments is used to find suitable method to be mocked.\n     * @see Mockito\n     */\n    <T> void when(T mock, Object... arguments) throws Exception;\n    \n    /**\n     * Allows to mock a private instance method based on method name and\n     * parameters when stubbing in doThrow()|doAnswer()|doNothing()|doReturn()\n     * style.\n     * <p>\n     * Example:\n     * </p>\n     * <pre>\n     * doThrow(new RuntimeException()).when(instance, &quot;methodName&quot;, parameter1, parameter2);\n     * </pre>\n     * </p>\n     * <p>\n     * Read more about those methods:\n     * </p>\n     * <p>\n     * {@link Mockito#doThrow(Throwable...)}\n     * </p>\n     * <p>\n     * {@link Mockito#doAnswer(Answer)}\n     * </p>\n     * <p>\n     * {@link Mockito#doNothing()}\n     * </p>\n     * <p>\n     * {@link Mockito#doReturn(Object)}\n     * </p>\n     *\n     * @param mock           the Mock\n     * @param methodToExpect name of method which have to mocked\n     * @param arguments      array of arguments of <code>methodToExpect</code>\n     * @see Mockito\n     */\n    <T> void when(T mock, String methodToExpect, Object... arguments) throws Exception;\n    \n    /**\n     * Allows to mock a static private method when stubbing in\n     * doThrow()|doAnswer()|doNothing()|doReturn() style.\n     * <p>\n     * Example:\n     * <pre>\n     * doThrow(new RuntimeException()).when(MyClass.class, method(&quot;myMethod&quot;)).withNoArguments();\n     * </pre>\n     * </p>\n     * <p>\n     * Read more about those methods:\n     * </p>\n     * <p>\n     * {@link Mockito#doThrow(Throwable...)}\n     * </p>\n     * <p>\n     * {@link Mockito#doAnswer(Answer)}\n     * </p>\n     * <p>\n     * {@link Mockito#doNothing()}\n     * </p>\n     * <p>\n     * {@link Mockito#doReturn(Object)}\n     * </p>\n     *\n     * @param classMock class owner of private static method\n     * @param method    private static method to be mocked\n     * @see Mockito\n     */\n    <T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception;\n    \n    /**\n     * Allows to mock a static private method based on the parameters when\n     * stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style.\n     * <p>\n     * Example:\n     * <pre>\n     * doThrow(new RuntimeException()).when(MyClass.class, parameter1, parameter2);\n     * </pre>\n     * </p>\n     * <p>\n     * Read more about those methods:\n     * </p>\n     * <p>\n     * {@link Mockito#doThrow(Throwable...)}\n     * </p>\n     * <p>\n     * {@link Mockito#doAnswer(Answer)}\n     * </p>\n     * <p>\n     * {@link Mockito#doNothing()}\n     * </p>\n     * <p>\n     * {@link Mockito#doReturn(Object)}\n     * </p>\n     *\n     * @param classMock class owner of private static method\n     * @param arguments array of arguments is used to find suitable method to be mocked.\n     * @see Mockito\n     */\n    <T> void when(Class<T> classMock, Object... arguments) throws Exception;\n    \n    /**\n     * Allows to mock a static private method based on method name and\n     * parameters when stubbing in doThrow()|doAnswer()|doNothing()|doReturn()\n     * style.\n     * <p>\n     * Example:\n     * <pre>\n     * doThrow(new RuntimeException()).when(MyClass.class, &quot;methodName&quot;, parameter1, parameter2);\n     * </pre>\n     * </p>\n     * <p>\n     * Read more about those methods:\n     * </p>\n     * <p>\n     * {@link Mockito#doThrow(Throwable...)}\n     * </p>\n     * <p>\n     * {@link Mockito#doAnswer(Answer)}\n     * </p>\n     * <p>\n     * {@link Mockito#doNothing()}\n     * </p>\n     * <p>\n     * {@link Mockito#doReturn(Object)}\n     * </p>\n     *\n     * @param classMock      the class owner of static private method\n     * @param methodToExpect name of method which have to mocked\n     * @param arguments      array of arguments of <code>methodToExpect</code>\n     * @see Mockito\n     */\n    <T> void when(Class<T> classMock, String methodToExpect, Object... arguments) throws Exception;\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/PrivatelyExpectedArguments.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */package org.powermock.api.mockito.expectation;\n\npublic interface PrivatelyExpectedArguments {\n\t<T> void withArguments(Object firstArgument, Object... additionalArguments) throws Exception;\n\n\t<T> void withNoArguments() throws Exception;\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithAnyArguments.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.expectation;\n\nimport org.mockito.stubbing.OngoingStubbing;\n\npublic interface WithAnyArguments<T> {\n\n    OngoingStubbing<T> withAnyArguments() throws Exception;\n\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithExpectedArguments.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.expectation;\n\nimport org.mockito.stubbing.OngoingStubbing;\n\npublic interface WithExpectedArguments<T> {\n\n\tOngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception;\n\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithExpectedParameterTypes.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.expectation;\n\npublic interface WithExpectedParameterTypes<T> {\n\n\tWithExpectedArguments<T> withParameterTypes(Class<?> parameterType, Class<?>... additionalParameterTypes);\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithOrWithoutExpectedArguments.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.expectation;\n\npublic interface WithOrWithoutExpectedArguments<T> extends WithExpectedArguments<T>, WithoutExpectedArguments<T> {\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithoutExpectedArguments.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.expectation;\n\nimport org.mockito.stubbing.OngoingStubbing;\n\npublic interface WithoutExpectedArguments<T> {\n\n    OngoingStubbing<T> withNoArguments() throws Exception;\n\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/reporter/MockitoPowerMockReporter.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.expectation.reporter;\n\nimport org.powermock.api.mockito.ClassNotPreparedException;\nimport org.powermock.core.reporter.PowerMockReporter;\n\nimport static org.powermock.utils.StringJoiner.join;\n\npublic class MockitoPowerMockReporter implements PowerMockReporter {\n\n    @Override\n    public <T> void classNotPrepared(Class<T> type) {\n        throw new ClassNotPreparedException(join(String.format(\"The class %s not prepared for test.\", type.getName()),\n                \"To prepare this class, add class to the '@PrepareForTest' annotation.\",\n                \"In case if you don't use this annotation, add the annotation on class or  method level. \"));\n    }\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/PowerMockitoCore.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal;\n\nimport org.mockito.MockSettings;\nimport org.mockito.Mockito;\nimport org.mockito.stubbing.Answer;\nimport org.mockito.stubbing.Stubber;\nimport org.mockito.verification.VerificationMode;\nimport org.powermock.api.mockito.expectation.PowerMockitoStubber;\nimport org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl;\nimport org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl;\nimport org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator;\nimport org.powermock.api.mockito.internal.stubbing.PowerMockCallRealMethod;\nimport org.powermock.api.mockito.internal.verification.DefaultConstructorArgumentsVerification;\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.classloader.ClassloaderWrapper;\nimport org.powermock.core.spi.NewInvocationControl;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Method;\nimport java.util.concurrent.Callable;\n\nimport static org.powermock.utils.Asserts.assertNotNull;\n\npublic class PowerMockitoCore {\n    \n    private static final PowerMockCallRealMethod POWER_MOCK_CALL_REAL_METHOD = new PowerMockCallRealMethod();\n    \n    private static final String NO_OBJECT_CREATION_ERROR_MESSAGE_TEMPLATE = \"No instantiation of class %s was recorded during the test. Note that only expected object creations (e.g. those using whenNew(..)) can be verified.\";\n    \n    public PowerMockitoStubber doAnswer(final Answer answer) {\n        return doAnswer(new Callable<Stubber>() {\n            @Override\n            public Stubber call() throws Exception {\n                return Mockito.doAnswer(answer);\n            }\n        });\n    }\n    \n    public PowerMockitoStubber doThrow(final Throwable toBeThrown) {\n        return doAnswer(new Callable<Stubber>() {\n            @Override\n            public Stubber call() throws Exception {\n                return Mockito.doThrow(toBeThrown);\n            }\n        });\n    }\n    \n    public PowerMockitoStubber doCallRealMethod() {\n        return doAnswer(new Callable<Stubber>() {\n            @Override\n            public Stubber call() throws Exception {\n                return Mockito.doCallRealMethod();\n            }\n        });\n    }\n    \n    public PowerMockitoStubber doNothing() {\n        return doAnswer(new Callable<Stubber>() {\n            @Override\n            public Stubber call() throws Exception {\n                return Mockito.doNothing();\n            }\n        });\n    }\n    \n    public PowerMockitoStubber doReturn(final Object toBeReturned) {\n        return doAnswer(new Callable<Stubber>() {\n            @Override\n            public Stubber call() throws Exception {\n                return Mockito.doReturn(toBeReturned);\n            }\n        });\n    }\n    \n    public PowerMockitoStubber doAnswer(final Object toBeReturned, final Object... othersToBeReturned) {\n        return doAnswer(new Callable<Stubber>() {\n            @Override\n            public Stubber call() throws Exception {\n                return Mockito.doReturn(toBeReturned, othersToBeReturned);\n            }\n        });\n    }\n    \n    public <T> DefaultConstructorArgumentsVerification<T> verifyNew(final Class<T> mock, final VerificationMode mode) {\n        assertNotNull(mock, \"Class to verify cannot be null\");\n        assertNotNull(mode, \"Verify mode cannot be null\");\n\n        @SuppressWarnings(\"unchecked\") MockitoNewInvocationControl<T> invocationControl = (MockitoNewInvocationControl<T>) MockRepository.getNewInstanceControl(mock);\n    \n        assertNotNull(invocationControl, String.format(NO_OBJECT_CREATION_ERROR_MESSAGE_TEMPLATE, Whitebox.getType(mock).getName()));\n    \n        invocationControl.verify(mode);\n        //noinspection unchecked\n        return new DefaultConstructorArgumentsVerification<T>((NewInvocationControl<T>) invocationControl, mock);\n    }\n    \n    public <T> T spy(final T object) {\n        MockSettings mockSettings = Mockito.withSettings()\n                                           .spiedInstance(object)\n                                           .defaultAnswer(POWER_MOCK_CALL_REAL_METHOD);\n        //noinspection unchecked\n        return DefaultMockCreator.mock((Class<T>) Whitebox.getType(object), false, true, object, mockSettings, (Method[]) null);\n    }\n    \n    private PowerMockitoStubber doAnswer(final Callable<Stubber> callable) {\n        final Stubber stubber = ClassloaderWrapper.runWithClass(callable);\n        return new PowerMockitoStubberImpl(stubber);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoInjectingAnnotationEngine.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.configuration;\n\nimport org.mockito.Mock;\nimport org.mockito.internal.MockitoCore;\nimport org.mockito.internal.configuration.InjectingAnnotationEngine;\nimport org.mockito.internal.configuration.plugins.Plugins;\nimport org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator;\n\n/**\n * The same as {@link InjectingAnnotationEngine} with the exception that it\n * doesn't create/injects mocks annotated with the standard annotations such as\n * {@link Mock}.\n */\npublic class PowerMockitoInjectingAnnotationEngine extends InjectingAnnotationEngine {\n\n    @SuppressWarnings(\"deprecation\")\n    @Override\n    public AutoCloseable process(Class<?> context, Object testClass) {\n        // this will create @Spies:\n        new PowerMockitoSpyAnnotationEngine().process(context, testClass);\n        \n        preLoadPluginLoader();\n        \n        // this injects mocks\n        injectMocks(testClass);\n        return null;\n    }\n    \n    private void preLoadPluginLoader() {\n        final ClassLoader originalCL = Thread.currentThread().getContextClassLoader();\n\n        Thread.currentThread().setContextClassLoader(DefaultMockCreator.class.getClassLoader());\n        \n        try {\n            MockitoCore mc = new MockitoCore();\n            Plugins.getMockMaker();\n        } finally {\n            Thread.currentThread().setContextClassLoader(originalCL);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoSpyAnnotationEngine.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.configuration;\n\nimport org.mockito.Captor;\nimport org.mockito.Mock;\nimport org.mockito.Spy;\nimport org.mockito.exceptions.base.MockitoException;\nimport org.mockito.internal.configuration.SpyAnnotationEngine;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Field;\n\n/**\n * More or less a copy of the {@link SpyAnnotationEngine} but it uses\n * {@link PowerMockito#spy(Object)} instead.\n */\npublic class PowerMockitoSpyAnnotationEngine extends SpyAnnotationEngine {\n\n\t@SuppressWarnings(\"deprecation\")\n\t@Override\n\tpublic AutoCloseable process(Class<?> context, Object testClass) {\n\t\tField[] fields = context.getDeclaredFields();\n\t\tfor (Field field : fields) {\n\t\t\tif (field.isAnnotationPresent(Spy.class)) {\n\t\t\t\ttry {\n\t\t\t\t\tWhitebox.invokeMethod(this, Spy.class, field, new Class<?>[] { Mock.class,\n\t\t\t\t\t\t\torg.mockito.Mock.class, Captor.class });\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (Exception e1) {\n\t\t\t\t\tthrow new RuntimeException(e1);\n\t\t\t\t}\n\t\t\t\tboolean wasAccessible = field.isAccessible();\n\t\t\t\tfield.setAccessible(true);\n\t\t\t\ttry {\n\t\t\t\t\tObject instance = field.get(testClass);\n\t\t\t\t\tif (instance == null) {\n\t\t\t\t\t\tthrow new MockitoException(\"Cannot create a @Spy for '\" + field.getName()\n\t\t\t\t\t\t\t\t+ \"' field because the *instance* is missing\\n\" + \"Example of correct usage of @Spy:\\n\"\n\t\t\t\t\t\t\t\t+ \"   @Spy List mock = new LinkedList();\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tfield.set(testClass, PowerMockito.spy(instance));\n\t\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\t\tthrow new MockitoException(\"Problems initiating spied field \" + field.getName(), e);\n\t\t\t\t} finally {\n\t\t\t\t\tfield.setAccessible(wasAccessible);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/exceptions/StackTraceCleanerProvider.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.internal.exceptions;\n\nimport org.mockito.exceptions.stacktrace.StackTraceCleaner;\n\npublic class StackTraceCleanerProvider implements org.mockito.plugins.StackTraceCleanerProvider {\n    @Override\n    public StackTraceCleaner getStackTraceCleaner(final StackTraceCleaner defaultCleaner) {\n        return new StackTraceCleaner() {\n            @Override\n            public boolean isIn(StackTraceElement candidate) {\n                return defaultCleaner.isIn(candidate) && !candidate.getClassName().startsWith(\"org.powermock.\")\n                      && !candidate.getClassName().startsWith(\"sun.reflect.\")\n                      && !candidate.getClassName().startsWith(\"java.lang.reflect.\")\n                      && !candidate.getClassName().startsWith(\"jdk.internal.reflect.\")\n                      && candidate.getLineNumber() != -1;\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/DefaultMethodExpectationSetup.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.expectation;\n\nimport org.mockito.Mockito;\nimport org.mockito.stubbing.OngoingStubbing;\nimport org.powermock.api.mockito.expectation.WithOrWithoutExpectedArguments;\n\nimport java.lang.reflect.Method;\n\npublic class DefaultMethodExpectationSetup<T> implements WithOrWithoutExpectedArguments<T> {\n\n    private final Object object;\n\n    private final Method method;\n\n    public DefaultMethodExpectationSetup(Object object, Method method) {\n        if (object == null) {\n            throw new IllegalArgumentException(\"object to expect cannot be null\");\n        } else if (method == null) {\n            throw new IllegalArgumentException(\"method to expect cannot be null\");\n        }\n        this.object = object;\n        this.method = method;\n        this.method.setAccessible(true);\n    }\n\n    private static Object[] join(Object o, Object[] array) {\n        Object[] res = new Object[array.length + 1];\n        res[0] = o;\n        System.arraycopy(array, 0, res, 1, array.length);\n        return res;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    public OngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception {\n        if (additionalArguments == null || additionalArguments.length == 0) {\n            return (OngoingStubbing<T>) Mockito.when(method.invoke(object, firstArgument));\n        } else {\n            return (OngoingStubbing<T>) Mockito.when(method.invoke(object, join(firstArgument, additionalArguments)));\n        }\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    public OngoingStubbing<T> withNoArguments() throws Exception {\n        return (OngoingStubbing<T>) Mockito.when(method.invoke(object));\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/DefaultPrivatelyExpectedArguments.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.expectation;\n\nimport org.powermock.api.mockito.expectation.PrivatelyExpectedArguments;\n\nimport java.lang.reflect.Method;\n\npublic class DefaultPrivatelyExpectedArguments implements PrivatelyExpectedArguments {\n\n    private final Method method;\n    private final Object mock;\n\n    public DefaultPrivatelyExpectedArguments(Object mock, Method method) {\n        this.mock = mock;\n        this.method = method;\n        method.setAccessible(true);\n    }\n\n    @Override\n    public <T> void withArguments(Object firstArgument, Object... additionalArguments) throws Exception {\n        if (additionalArguments == null || additionalArguments.length == 0) {\n            method.invoke(mock, firstArgument);\n        } else {\n            Object[] allArgs = new Object[additionalArguments.length + 1];\n            allArgs[0] = firstArgument;\n            if (additionalArguments.length > 0) {\n                System.arraycopy(additionalArguments, 0, allArgs, 1, additionalArguments.length);\n            }\n            method.invoke(mock, allArgs);\n        }\n    }\n\n    @Override\n    public <T> void withNoArguments() throws Exception {\n        method.invoke(mock);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/DelegatingToConstructorsOngoingStubbing.java",
    "content": "/*\n * Copyright 2012 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.internal.expectation;\n\nimport org.mockito.ArgumentMatchers;\nimport org.mockito.stubbing.Answer;\nimport org.mockito.stubbing.OngoingStubbing;\nimport org.powermock.core.spi.support.InvocationSubstitute;\n\nimport java.lang.reflect.Constructor;\n\nimport static org.mockito.Mockito.when;\n\n/**\n * Implementation of OngoingStubbing that delegates invocations to all supplied ctors\n * @param <T>\n */\npublic class DelegatingToConstructorsOngoingStubbing<T> implements OngoingStubbing<T>{\n\n    private final OngoingStubbing<T> stubbing;\n    private final Constructor<?>[] ctors;\n\n    public DelegatingToConstructorsOngoingStubbing(Constructor<?>[] ctors, OngoingStubbing<T> stubbing) {\n        if(stubbing == null) {\n            throw new IllegalArgumentException(\"Internal error: Ongoing stubbing must be provided\");\n        }\n        this.ctors = ctors;\n        this.stubbing = stubbing;\n    }\n\n    @Override\n    public OngoingStubbing<T> thenReturn(final T value) {\n        stubbing.thenReturn(value);\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.thenReturn(value);\n            }\n        }.invoke();\n    }\n\n    @Override\n    public OngoingStubbing<T> thenReturn(final T value, final T... values) {\n        stubbing.thenReturn(value, values);\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.thenReturn(value, values);\n            }\n        }.invoke();\n    }\n\n    @Override\n    public OngoingStubbing<T> thenThrow(final Throwable... throwables) {\n        stubbing.thenThrow(throwables);\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.thenThrow(throwables);\n            }\n        }.invoke();\n    }\n    \n    @Override\n    public OngoingStubbing<T> thenThrow(final Class<? extends Throwable> throwableType) {\n        stubbing.thenThrow(throwableType);\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.thenThrow(throwableType);\n            }\n        }.invoke();\n    }\n \n    @Override\n    public OngoingStubbing<T> thenThrow(final Class<? extends Throwable> toBeThrown, final Class<? extends Throwable>[] nextToBeThrown) {\n        stubbing.thenThrow(toBeThrown, nextToBeThrown);\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.thenThrow(toBeThrown, nextToBeThrown);\n            }\n        }.invoke();\n    }\n\n    @Override\n    public OngoingStubbing<T> thenCallRealMethod() {\n        stubbing.thenCallRealMethod();\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.thenCallRealMethod();\n            }\n        }.invoke();\n    }\n\n    @Override\n    public OngoingStubbing<T> thenAnswer(final Answer<?> answer) {\n        stubbing.thenAnswer(answer);\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.thenAnswer(answer);\n            }\n        }.invoke();\n    }\n\n    @Override\n    public OngoingStubbing<T> then(final Answer<?> answer) {\n        stubbing.then(answer);\n        return new InvokeStubMethod() {\n            @Override\n            public void performStubbing(OngoingStubbing<T> when) {\n                when.then(answer);\n            }\n        }.invoke();\n    }\n\n    @Override\n    public <M> M getMock() {\n        return stubbing.getMock();\n    }\n\n\n    private abstract class InvokeStubMethod {\n        public OngoingStubbing<T> invoke() {\n            final InvocationSubstitute<T> mock = stubbing.getMock();\n            for (Constructor<?> constructor : ctors) {\n                final Class<?>[] parameterTypesForCtor = constructor.getParameterTypes();\n                Object[] paramArgs = new Object[parameterTypesForCtor.length];\n                for (int i = 0; i < parameterTypesForCtor.length; i++) {\n                    Class<?> paramType = parameterTypesForCtor[i];\n                    paramArgs[i] = ArgumentMatchers.nullable(paramType);\n                }\n                try {\n                    final OngoingStubbing<T> when = when(mock.performSubstitutionLogic(paramArgs));\n                    performStubbing(when);\n                } catch (Exception e) {\n                    throw new RuntimeException(\"PowerMock internal error\",e);\n                }\n            }\n\n            return stubbing;\n        }\n\n        public abstract void performStubbing(OngoingStubbing<T> when);\n\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/PowerMockitoStubberImpl.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.expectation;\n\nimport org.mockito.stubbing.Answer;\nimport org.mockito.stubbing.Stubber;\nimport org.powermock.api.mockito.expectation.PowerMockitoStubber;\nimport org.powermock.api.mockito.expectation.PrivatelyExpectedArguments;\nimport org.powermock.api.mockito.invocation.MockitoMethodInvocationControl;\nimport org.powermock.core.MockRepository;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Method;\n\n/**\n * Extension of the standard Mocktio stubber implementation that also support\n * PowerMockito created mocks.\n */\npublic class PowerMockitoStubberImpl implements PowerMockitoStubber, Stubber {\n    \n    private final Stubber stubber;\n    \n    public PowerMockitoStubberImpl(final Stubber stubber) {this.stubber = stubber;}\n    \n    @Override\n    public <T> T when(final T instanceMock) {\n        final MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(instanceMock);\n        final T returnValue;\n        if (invocationControl == null) {\n            returnValue = stubber.when(instanceMock);\n        } else {\n            final Object mock = invocationControl.getMockHandlerAdaptor().getMock();\n            stubber.when(mock);\n            returnValue = instanceMock;\n        }\n        return returnValue;\n    }\n    \n    @Override\n    public Stubber doThrow(final Throwable... toBeThrown) {return stubber.doThrow(toBeThrown);}\n    \n    @Override\n    public Stubber doThrow(final Class<? extends Throwable> toBeThrown) {return stubber.doThrow(toBeThrown);}\n    \n    @Override\n    public Stubber doThrow(final Class<? extends Throwable> toBeThrown, final Class<? extends Throwable>[] nextToBeThrown) {return stubber.doThrow(toBeThrown, nextToBeThrown);}\n    \n    @Override\n    public Stubber doAnswer(final Answer answer) {return stubber.doAnswer(answer);}\n    \n    @Override\n    public Stubber doNothing() {return stubber.doNothing();}\n    \n    @Override\n    public Stubber doReturn(final Object toBeReturned) {return stubber.doReturn(toBeReturned);}\n    \n    @Override\n    public Stubber doReturn(final Object toBeReturned,\n                            final Object... nextToBeReturned) {return stubber.doReturn(toBeReturned, nextToBeReturned);}\n    \n    @Override\n    public Stubber doCallRealMethod() {return stubber.doCallRealMethod();}\n    \n    @Override\n    public void when(Class<?> classMock) {\n        MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getStaticMethodInvocationControl(classMock);\n        final Object mock = invocationControl.getMockHandlerAdaptor().getMock();\n        stubber.when(mock);\n    }\n    \n    @Override\n    public <T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception {\n        assertNotNull(mock, \"mock\");\n        assertNotNull(method, \"Method\");\n        this.when(mock);\n        return new DefaultPrivatelyExpectedArguments(mock, method);\n    }\n    \n    @Override\n    public <T> void when(T mock, Object... arguments) throws Exception {\n        assertNotNull(mock, \"mock\");\n        this.when(mock);\n        Whitebox.invokeMethod(mock, arguments);\n    }\n    \n    @Override\n    public <T> void when(T mock, String methodToExpect, Object... arguments) throws Exception {\n        assertNotNull(mock, \"mock\");\n        assertNotNull(methodToExpect, \"methodToExpect\");\n        this.when(mock);\n        Whitebox.invokeMethod(mock, methodToExpect, arguments);\n    }\n    \n    @Override\n    public <T> void when(Class<T> classMock, Object... arguments) throws Exception {\n        assertNotNull(classMock, \"classMock\");\n        when(classMock);\n        Whitebox.invokeMethod(classMock, arguments);\n    }\n    \n    @Override\n    public <T> void when(Class<T> classMock, String methodToExpect, Object... parameters) throws Exception {\n        assertNotNull(classMock, \"classMock\");\n        assertNotNull(methodToExpect, \"methodToExpect\");\n        when(classMock);\n        Whitebox.invokeMethod(classMock, methodToExpect, parameters);\n    }\n    \n    @Override\n    public <T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception {\n        assertNotNull(classMock, \"classMock\");\n        assertNotNull(method, \"Method\");\n        when(classMock);\n        return new DefaultPrivatelyExpectedArguments(classMock, method);\n    }\n    \n    private void assertNotNull(Object object, String name) {\n        if (object == null) {\n            throw new IllegalArgumentException(name + \" cannot be null\");\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/InvocationControlAssertionError.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.internal.invocation;\n\nimport org.powermock.core.spi.support.InvocationSubstitute;\nimport org.powermock.reflect.Whitebox;\n\nimport java.util.regex.Matcher;\n\npublic class InvocationControlAssertionError {\n    private static final String AT = \"at\";\n    private static final String ERROR_LOCATION_MARKER = \"->\";\n    private static final String COLON_NEWLINE = \":\\n\";\n    private static final String NEWLINE_POINT = \"\\n.\";\n    private static final String HERE_TEXT = \"here:\\n\";\n    private static final String UNDESIRED_INVOCATION_TEXT = \" Undesired invocation:\";\n    private static final String POWER_MOCKITO_CLASS_NAME = \"org.powermock.api.mockito.PowerMockito\";\n\n    public static void updateErrorMessageForVerifyNoMoreInteractions(AssertionError errorToUpdate) {\n        /*\n         * VerifyNoMoreInteractions failed, we need to update the error message.\n         */\n        String verifyNoMoreInteractionsInvocation = null;\n        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();\n        for (int i = stackTrace.length - 1; i >= 0; i--) {\n            final StackTraceElement stackTraceElement = stackTrace[i];\n            if (stackTraceElement.getClassName().equals(POWER_MOCKITO_CLASS_NAME)\n                        && stackTraceElement.getMethodName().equals(\"verifyNoMoreInteractions\")) {\n                final int invocationStackTraceIndex;\n                if (stackTrace[i + 1].getClassName().equals(POWER_MOCKITO_CLASS_NAME)\n                            && stackTrace[i + 1].getMethodName().equals(\"verifyZeroInteractions\")) {\n                    invocationStackTraceIndex = i + 2;\n                } else {\n                    invocationStackTraceIndex = i + 1;\n                }\n                verifyNoMoreInteractionsInvocation = stackTrace[invocationStackTraceIndex].toString();\n            }\n        }\n\n        if (verifyNoMoreInteractionsInvocation == null) {\n            // Something unexpected happened, just return\n            return;\n        }\n        String message = errorToUpdate.getMessage();\n        StringBuilder builder = new StringBuilder();\n        builder.append(message);\n        final int indexOfFirstAt = message.indexOf(AT);\n        final int startOfVerifyNoMoreInteractionsInvocation = indexOfFirstAt + AT.length() + 1;\n        final int endOfVerifyNoMoreInteractionsInvocation = message.indexOf('\\n', indexOfFirstAt + AT.length());\n        builder.replace(startOfVerifyNoMoreInteractionsInvocation, endOfVerifyNoMoreInteractionsInvocation,\n                        verifyNoMoreInteractionsInvocation);\n        builder.delete(builder.indexOf(\"\\n\", endOfVerifyNoMoreInteractionsInvocation + 1), builder.lastIndexOf(\"\\n\"));\n        Whitebox.setInternalState(errorToUpdate, \"detailMessage\", builder.toString());\n    }\n\n    public static void updateErrorMessageForMethodInvocation(AssertionError errorToUpdate) {\n        /*\n         * We failed to verify the new substitution mock. This happens when, for\n         * example, the user has done something like\n         * whenNew(MyClass.class).thenReturn(myMock).times(3) when in fact an\n         * instance of MyClass has been created less or more times than 3.\n         */\n        Whitebox.setInternalState(errorToUpdate, \"detailMessage\", \"\\n\" + changeMessageContent(errorToUpdate.getMessage()));\n    }\n\n    public static void throwAssertionErrorForNewSubstitutionFailure(AssertionError oldError, Class<?> type) {\n        /*\n         * We failed to verify the new substitution mock. This happens when, for\n         * example, the user has done something like\n         * whenNew(MyClass.class).thenReturn(myMock).times(3) when in fact an\n         * instance of MyClass has been created less or more times than 3.\n         */\n        final String newSubsitutionClassName = InvocationSubstitute.class.getSimpleName();\n        final String newSubsitutionClassNameInMockito = newSubsitutionClassName.substring(0, 1).toLowerCase()\n                                                                + newSubsitutionClassName.substring(1);\n        String message = oldError.getMessage();\n        final String newSubsitutionMethodName = InvocationSubstitute.class.getDeclaredMethods()[0].getName();\n        message = message.replaceAll(newSubsitutionClassNameInMockito + \".\" + newSubsitutionMethodName, Matcher\n                                                                                                                .quoteReplacement(type.getName()));\n        message = message.replaceAll(\"method\", \"constructor\");\n        throw new AssertionError(changeMessageContent(message));\n    }\n\n    private static String changeMessageContent(String message) {\n        /*\n         * Temp fix: Remove powermock internal \"at locations\" (points to which\n         * line the expectation went wrong in Mockito). We should try to find\n         * the real ones instead\n         */\n        StringBuilder builder = removeFailureLocations(message);\n        // Remove \"Undesired invocation:\"\n        removeText(builder, UNDESIRED_INVOCATION_TEXT);\n\n        removeAndReplaceText(builder, HERE_TEXT, ' ');\n\n        removeAndReplaceText(builder, COLON_NEWLINE, ' ');\n    \n        return builder.toString().trim();\n    }\n\n    private static StringBuilder removeFailureLocations(String message) {\n        StringBuilder builder = new StringBuilder();\n        builder.append(message);\n        int indexOfBeginLocation = builder.indexOf(ERROR_LOCATION_MARKER);\n        while (indexOfBeginLocation > 0) {\n            int indexOfLocationEnd = builder.indexOf(\"\\n\", indexOfBeginLocation);\n            builder.delete(indexOfBeginLocation, indexOfLocationEnd < 0 ? builder.length() : indexOfLocationEnd + 1);\n            indexOfBeginLocation = builder.indexOf(ERROR_LOCATION_MARKER);\n        }\n        return builder;\n    }\n\n    private static void removeAndReplaceText(StringBuilder builder, String text, char appender) {\n        int currentTextIndex = builder.indexOf(text);\n        int previousTextIndex;\n        boolean isSingleConcat = true;\n    \n        while (currentTextIndex > 0) {\n            previousTextIndex = currentTextIndex;\n            builder.delete(currentTextIndex, currentTextIndex + text.length());\n            currentTextIndex = builder.indexOf(text);\n            \n            final int length = builder.length();\n            \n            if (isLastFinding(currentTextIndex) && !isSingleConcat) {\n                final int start = builder.charAt(length - 1) == '\\n' ? length - 1 : length;\n                builder.replace(start, length, \".\");\n            } else {\n                final int end = previousTextIndex < length ? previousTextIndex + 1 : length;\n                builder.replace(\n                    previousTextIndex, end,\n                    String.valueOf(builder.charAt(previousTextIndex)).toLowerCase()\n                );\n                builder.insert(previousTextIndex, String.valueOf(appender));\n                currentTextIndex++;\n                isSingleConcat = false;\n            }\n        }\n    }\n\n    private static boolean isLastFinding(int index) {\n        return index < 0;\n    }\n\n    private static void removeText(StringBuilder builder, String text) {\n        int textIndex = builder.indexOf(text);\n        while (textIndex > 0) {\n            builder.delete(textIndex, textIndex + text.length());\n            textIndex = builder.indexOf(text);\n        }\n    }\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/MockitoNewInvocationControl.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.internal.invocation;\n\nimport org.mockito.Mockito;\nimport org.mockito.exceptions.base.MockitoAssertionError;\nimport org.mockito.stubbing.OngoingStubbing;\nimport org.mockito.verification.VerificationMode;\nimport org.powermock.core.spi.NewInvocationControl;\nimport org.powermock.core.spi.support.InvocationSubstitute;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Constructor;\n\npublic class MockitoNewInvocationControl<T> implements NewInvocationControl<OngoingStubbing<T>> {\n\tprivate final InvocationSubstitute<T> substitute;\n\n\tpublic MockitoNewInvocationControl(InvocationSubstitute<T> substitute) {\n\t\tif (substitute == null) {\n\t\t\tthrow new IllegalArgumentException(\"Internal error: substitute cannot be null.\");\n\t\t}\n\t\tthis.substitute = substitute;\n    }\n\n    @Override\n\tpublic Object invoke(Class<?> type, Object[] args, Class<?>[] sig) throws Exception {\n\t\tConstructor<?> constructor = WhiteboxImpl.getConstructor(type, sig);\n\t\tif (constructor.isVarArgs()) {\n\t\t\tObject varArgs =  args[args.length - 1];\n            final int varArgsLength = Array.getLength(varArgs);\n            Object[] oldArgs = args;\n            args = new Object[args.length + varArgsLength - 1];\n            System.arraycopy(oldArgs, 0, args, 0, oldArgs.length - 1);\n            for (int i = oldArgs.length - 1, j=0; i < args.length; i++, j++) {\n                args[i] = Array.get(varArgs, j);\n            }\n\t\t}\n\t\ttry {\n\t\t\treturn substitute.performSubstitutionLogic(args);\n\t\t} catch (MockitoAssertionError e) {\n\t\t\tInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type);\n\t\t}\n\n\t\t// Won't happen\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic OngoingStubbing<T> expectSubstitutionLogic(Object... arguments) throws Exception {\n        return Mockito.when(substitute.performSubstitutionLogic(arguments));\n\t}\n\n\tpublic InvocationSubstitute<T> getSubstitute() {\n\t\treturn substitute;\n\t}\n\n\t@Override\n\tpublic synchronized Object replay(Object... mocks) {\n\t\treturn null;\n\t}\n    \n    public synchronized void verify(final VerificationMode verificationMode) {\n        Mockito.verify(substitute, verificationMode);\n    }\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic synchronized Object reset(Object... mocks) {\n\t\tMockito.reset(substitute);\n\t\treturn null;\n\t}\n\n\tpublic void verifyNoMoreInteractions() {\n\t\ttry {\n\t\t\tMockito.verifyNoMoreInteractions(substitute);\n\t\t} catch (MockitoAssertionError e) {\n\t\t\tInvocationControlAssertionError.updateErrorMessageForVerifyNoMoreInteractions(e);\n\t\t\tthrow e;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/AbstractMockCreator.java",
    "content": "package org.powermock.api.mockito.internal.mockcreation;\n\nimport org.powermock.core.agent.JavaAgentClassRegister;\n\npublic abstract class AbstractMockCreator implements MockCreator {\n\n    private JavaAgentClassRegister agentClassRegister;\n\n    <T> void validateType(Class<T> type, boolean isStatic, boolean isSpy) {\n        createTypeValidator(type, isStatic, isSpy).validate();\n    }\n\n    private <T> MockTypeValidator<T> createTypeValidator(Class<T> type, boolean isStatic, boolean isSpy) {\n        return MockTypeValidatorFactory.createValidator(type, isStatic, isSpy, agentClassRegister);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/DefaultMockCreator.java",
    "content": "/*\r\n *   Copyright 2016 the original author or authors.\r\n *\r\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *   you may not use this file except in compliance with the License.\r\n *   You may obtain a copy of the License at\r\n *\r\n *        http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *   Unless required by applicable law or agreed to in writing, software\r\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *   See the License for the specific language governing permissions and\r\n *   limitations under the License.\r\n *\r\n */\r\npackage org.powermock.api.mockito.internal.mockcreation;\r\n\r\nimport org.mockito.MockSettings;\r\nimport org.mockito.Mockito;\r\nimport org.powermock.api.mockito.invocation.MockitoMethodInvocationControl;\r\nimport org.powermock.core.ClassReplicaCreator;\r\nimport org.powermock.core.DefaultFieldValueGenerator;\r\nimport org.powermock.core.MockRepository;\r\nimport org.powermock.core.classloader.MockClassLoader;\r\nimport org.powermock.reflect.Whitebox;\r\n\r\nimport java.lang.reflect.Method;\r\nimport java.lang.reflect.Modifier;\r\n\r\nimport static org.powermock.utils.Asserts.assertNotNull;\r\n\r\npublic class DefaultMockCreator extends AbstractMockCreator {\r\n    \r\n    private static final DefaultMockCreator MOCK_CREATOR = new DefaultMockCreator();\r\n    \r\n    @SuppressWarnings(\"unchecked\")\r\n    public static <T> T mock(Class<T> type, boolean isStatic, boolean isSpy, Object delegator,\r\n                             MockSettings mockSettings, Method... methods) {\r\n        return MOCK_CREATOR.createMock(type, isStatic, isSpy, delegator, mockSettings, methods);\r\n    }\r\n    \r\n    @SuppressWarnings(\"unchecked\")\r\n    public <T> T createMock(Class<T> type, boolean isStatic, boolean isSpy, Object delegatorCandidate,\r\n                            MockSettings mockSettings, Method... methods) {\r\n        \r\n        assertNotNull(type, \"The class to mock cannot be null\");\r\n        \r\n        validateType(type, isStatic, isSpy);\r\n    \r\n        registerAfterMethodRunner();\r\n    \r\n        return doCreateMock(type, isStatic, isSpy, delegatorCandidate, mockSettings, methods);\r\n    }\r\n    \r\n    private <T> T doCreateMock(final Class<T> type, final boolean isStatic, final boolean isSpy, final Object delegatorCandidate, final MockSettings mockSettings, final Method[] methods) {\r\n        final Class<T> typeToMock = getMockType(type);\r\n        \r\n        final Object delegator = isSpy && delegatorCandidate == null ? new Object() : delegatorCandidate;\r\n    \r\n        final MockData<T> mockData = createMethodInvocationControl(typeToMock, methods, delegator, mockSettings);\r\n        \r\n        T mock = mockData.getMock();\r\n        \r\n        if (isFinalJavaSystemClass(type) && !isStatic) {\r\n            mock = Whitebox.newInstance(type);\r\n            DefaultFieldValueGenerator.fillWithDefaultValues(mock);\r\n        }\r\n        \r\n        putMethodInvocationControlToRepository(type, isStatic, mockData, mock);\r\n    \r\n        return mock;\r\n    }\r\n    \r\n    private void registerAfterMethodRunner() {\r\n        MockRepository.addAfterMethodRunner(new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                Mockito.reset();\r\n            }\r\n        });\r\n    }\r\n    \r\n    private <T> void putMethodInvocationControlToRepository(final Class<T> type, final boolean isStatic, final MockData<T> mockData, final T mock) {\r\n        if (isStatic) {\r\n            MockRepository.putStaticMethodInvocationControl(type, mockData.getMethodInvocationControl());\r\n        } else {\r\n            MockRepository.putInstanceMethodInvocationControl(mock, mockData.getMethodInvocationControl());\r\n        }\r\n    }\r\n    \r\n    private <T> Class<T> getMockType(final Class<T> type) {\r\n        final Class<T> typeToMock;\r\n        if (isFinalJavaSystemClass(type)) {\r\n            typeToMock = new ClassReplicaCreator().createClassReplica(type);\r\n        } else {\r\n            typeToMock = type;\r\n        }\r\n        return typeToMock;\r\n    }\r\n    \r\n    private static <T> boolean isFinalJavaSystemClass(Class<T> type) {\r\n        return type.getName().startsWith(\"java.\") && Modifier.isFinal(type.getModifiers());\r\n    }\r\n    \r\n    @SuppressWarnings(\"unchecked\")\r\n    private <T> MockData<T> createMethodInvocationControl(Class<T> type, Method[] methods, Object delegator, MockSettings mockSettings) {\r\n        final T mock = Mockito.mock(type, mockSettings != null ? mockSettings : Mockito.withSettings());\r\n    \r\n        cacheMockClass(mock.getClass());\r\n        \r\n        return new MockData<T>(new MockitoMethodInvocationControl(delegator, mock, methods), mock);\r\n    }\r\n    \r\n    private void cacheMockClass(final Class<?> mockClass) {\r\n        ClassLoader classLoader = mockClass.getClassLoader();\r\n        if (classLoader instanceof MockClassLoader) {\r\n            MockClassLoader mcl = (MockClassLoader) classLoader;\r\n            mcl.cache(mockClass);\r\n        }\r\n    }\r\n    \r\n    /**\r\n     * Class that encapsulate a mock and its corresponding invocation control.\r\n     */\r\n    private static class MockData<T> {\r\n        private final MockitoMethodInvocationControl methodInvocationControl;\r\n        \r\n        private final T mock;\r\n        \r\n        private MockData(MockitoMethodInvocationControl methodInvocationControl, T mock) {\r\n            this.methodInvocationControl = methodInvocationControl;\r\n            this.mock = mock;\r\n        }\r\n        \r\n        private MockitoMethodInvocationControl getMethodInvocationControl() {\r\n            return methodInvocationControl;\r\n        }\r\n        \r\n        private T getMock() {\r\n            return mock;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockCreator.java",
    "content": "package org.powermock.api.mockito.internal.mockcreation;\n\nimport java.lang.reflect.Method;\n\n/**\n * An implementer of interface is reasonable for creating of an mocked instance of specific type.\n */\npublic interface MockCreator {\n    <T> T createMock(Class<T> type, boolean isStatic, boolean isSpy, Object delegator, org.mockito.MockSettings mockSettings, Method... methods);\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidator.java",
    "content": "package org.powermock.api.mockito.internal.mockcreation;\n\n/**\n *\n */\npublic interface MockTypeValidator<T> {\n    void validate();\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidatorFactory.java",
    "content": "package org.powermock.api.mockito.internal.mockcreation;\n\nimport org.powermock.api.mockito.expectation.reporter.MockitoPowerMockReporter;\nimport org.powermock.core.agent.JavaAgentClassRegister;\nimport org.powermock.core.classloader.PowerMockModified;\nimport org.powermock.core.reporter.PowerMockReporter;\n\n/**\n *\n */\npublic class MockTypeValidatorFactory {\n\n    public static <T> MockTypeValidator<T> createValidator(Class<T> type, boolean isStatic, boolean isSpy, JavaAgentClassRegister agentClassRegister) {\n        if (!isStatic || isSpy || isLoadedByBootstrap(type)) {\n            return new NullMockTypeValidator<T>();\n        } else if (agentClassRegister == null) {\n            return new DefaultMockTypeValidator<T>(type);\n        } else {\n            return new JavaAgentMockTypeValidator<T>(type, agentClassRegister);\n        }\n\n    }\n\n    private static boolean isLoadedByBootstrap(Class type) {\n        return type.getClassLoader() == null;\n    }\n\n    private static class DefaultMockTypeValidator<T> extends AbstractMockTypeValidator<T> {\n\n        DefaultMockTypeValidator(Class<T> type) {\n            super(type);\n        }\n\n        @Override\n        public void validate() {\n            if (!isModifiedByPowerMock()) {\n                reporter.classNotPrepared(type);\n            }\n        }\n\n        private boolean isModifiedByPowerMock() {\n            return PowerMockModified.class.isAssignableFrom(type);\n        }\n    }\n\n    private static class JavaAgentMockTypeValidator<T> extends AbstractMockTypeValidator<T> {\n\n        private final JavaAgentClassRegister agentClassRegister;\n\n        private JavaAgentMockTypeValidator(Class<T> type, JavaAgentClassRegister agentClassRegister) {\n            super(type);\n            this.agentClassRegister = agentClassRegister;\n        }\n\n        @Override\n        public void validate() {\n            if (!isModifiedByAgent()) {\n                reporter.classNotPrepared(type);\n            }\n        }\n\n        private boolean isModifiedByAgent() {\n            return agentClassRegister.isModifiedByAgent(type.getClassLoader(), type.getName());\n        }\n    }\n\n    private abstract static class AbstractMockTypeValidator<T> implements MockTypeValidator<T> {\n        final PowerMockReporter reporter;\n        final Class<T> type;\n\n        private AbstractMockTypeValidator(Class<T> type) {\n            this.type = type;\n            this.reporter = new MockitoPowerMockReporter();\n        }\n\n        @Override\n        public abstract void validate();\n\n    }\n\n    private static class NullMockTypeValidator<T> implements MockTypeValidator<T> {\n        @Override\n        public void validate() {\n            // NUll validator validates nothing\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/RuntimeExceptionProxy.java",
    "content": "package org.powermock.api.mockito.internal.mockcreation;\n\npublic class RuntimeExceptionProxy extends RuntimeException {\n    public RuntimeExceptionProxy(Throwable t) {\n        super(t);\n    }\n}\n\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/MockitoRealMethodInvocation.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.internal.stubbing;\n\n\npublic class MockitoRealMethodInvocation {\n    private static final ThreadLocal<Boolean> handledByMockito = new ThreadLocal<Boolean>();\n    \n    private MockitoRealMethodInvocation() {\n    }\n    \n    public static void mockitoInvocationStarted() {\n        handledByMockito.set(true);\n    }\n    \n    public static void mockitoInvocationFinished() {\n        handledByMockito.set(false);\n    }\n    \n    public static boolean isHandledByMockito() {\n        final Boolean handled = handledByMockito.get();\n        return handled == null ? false : handled;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/PowerMockCallRealMethod.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.internal.stubbing;\n\nimport org.mockito.Mockito;\nimport org.mockito.invocation.InvocationOnMock;\nimport org.mockito.stubbing.Answer;\n\npublic class PowerMockCallRealMethod implements Answer {\n    @Override\n    public Object answer(InvocationOnMock invocation) throws Throwable {\n        MockitoRealMethodInvocation.mockitoInvocationStarted();\n        try {\n            return Mockito.CALLS_REAL_METHODS.answer(invocation);\n        } finally {\n            MockitoRealMethodInvocation.mockitoInvocationFinished();\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/verification/DefaultConstructorArgumentsVerification.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.verification;\n\nimport org.mockito.exceptions.base.MockitoAssertionError;\nimport org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError;\nimport org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl;\nimport org.powermock.api.mockito.verification.ConstructorArgumentsVerification;\nimport org.powermock.core.spi.NewInvocationControl;\n\npublic class DefaultConstructorArgumentsVerification<T> implements ConstructorArgumentsVerification {\n\n    private final MockitoNewInvocationControl<T> invocationControl;\n    private final Class<?> type;\n\n    @SuppressWarnings(\"unchecked\")\n    public DefaultConstructorArgumentsVerification(NewInvocationControl<T> invocationControl, Class<?> type) {\n        this.type = type;\n        this.invocationControl = (MockitoNewInvocationControl<T>) invocationControl;\n    }\n\n    @Override\n    public void withArguments(Object argument, Object... arguments) throws Exception {\n        final Object[] realArguments;\n        if (arguments == null) {\n            realArguments = new Object[]{argument, null};\n        } else {\n            realArguments = new Object[arguments.length + 1];\n            realArguments[0] = argument;\n            System.arraycopy(arguments, 0, realArguments, 1, arguments.length);\n        }\n        invokeSubstitute(realArguments);\n    }\n\n    private void invokeSubstitute(Object... arguments) throws Exception {\n        try {\n            invocationControl.getSubstitute().performSubstitutionLogic(arguments);\n        } catch (MockitoAssertionError e) {\n            InvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type);\n        }\n    }\n\n    @Override\n    public void withNoArguments() throws Exception {\n        invokeSubstitute();\n    }\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/verification/DefaultPrivateMethodVerification.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.verification;\n\nimport org.powermock.api.mockito.verification.PrivateMethodVerification;\nimport org.powermock.api.mockito.verification.WithOrWithoutVerifiedArguments;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.impl.ArrayMergerImpl;\n\nimport java.lang.reflect.Method;\n\npublic class DefaultPrivateMethodVerification implements PrivateMethodVerification {\n\n\tprivate final Object objectToVerify;\n\n\tpublic DefaultPrivateMethodVerification(Object objectToVerify) {\n\t\tthis.objectToVerify = objectToVerify;\n\t}\n\n\t@Override\n\tpublic void invoke(Object... arguments) throws Exception {\n\t\tWhitebox.invokeMethod(objectToVerify, arguments);\n\n\t}\n\n\t@Override\n\tpublic void invoke(String methodToExecute, Object... arguments) throws Exception {\n\t\tWhitebox.invokeMethod(objectToVerify, methodToExecute, (Object[]) arguments);\n\t}\n\n\t@Override\n\tpublic WithOrWithoutVerifiedArguments invoke(Method method) throws Exception {\n\t\treturn new VerificationArguments(method);\n\t}\n\n\tprivate class VerificationArguments implements WithOrWithoutVerifiedArguments {\n\t\tprivate final Method method;\n\n\t\tpublic VerificationArguments(Method method) {\n\t\t\tif (method == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"method cannot be null\");\n\t\t\t}\n\t\t\tthis.method = method;\n\t\t\tthis.method.setAccessible(true);\n\t\t}\n\n\t\t@Override\n\t\tpublic void withArguments(Object firstArgument, Object... additionalArguments) throws Exception {\n\t\t\tif (additionalArguments == null || additionalArguments.length == 0) {\n\t\t\t\tmethod.invoke(objectToVerify, firstArgument);\n\t\t\t} else {\n                Object[] arguments = new ArrayMergerImpl().mergeArrays(Object.class, new Object[]{firstArgument}, additionalArguments);\n                method.invoke(objectToVerify, arguments);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void withNoArguments() throws Exception {\n\t\t\tmethod.invoke(objectToVerify);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/verification/VerifyNoMoreInteractions.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.internal.verification;\n\nimport org.mockito.Mockito;\nimport org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl;\nimport org.powermock.api.mockito.invocation.MockitoMethodInvocationControl;\nimport org.powermock.core.MockRepository;\n\n/**\n * Verifies no more interactions, delegates to Mockito if PowerMockito doesn't\n * find a supplied mock.\n */\npublic class VerifyNoMoreInteractions {\n\n    public static void verifyNoMoreInteractions(Object... objects) {\n        for (Object mock : objects) {\n            if (mock instanceof Class<?>) {\n                verifyNoMoreInteractions((Class<?>) mock);\n            } else {\n                MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository\n                        .getInstanceMethodInvocationControl(mock);\n                if (invocationControl != null) {\n                    invocationControl.verifyNoMoreInteractions();\n                } else {\n                    /*\n                     * Delegate to Mockito if we have no handler registered for\n                     * this object.\n                     */\n                    Mockito.verifyNoMoreInteractions(mock);\n                }\n            }\n        }\n    }\n\n    private static void verifyNoMoreInteractions(Class<?>... types) {\n        for (Class<?> type : types) {\n            final MockitoMethodInvocationControl invocationHandler = (MockitoMethodInvocationControl) MockRepository\n                    .getStaticMethodInvocationControl(type);\n            if (invocationHandler != null) {\n                invocationHandler.verifyNoMoreInteractions();\n            }\n            MockitoNewInvocationControl<?> newInvocationControl = (MockitoNewInvocationControl<?>) MockRepository.getNewInstanceControl(type);\n            if (newInvocationControl != null) {\n                newInvocationControl.verifyNoMoreInteractions();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/InvocationFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.invocation;\n\nimport org.mockito.Mockito;\nimport org.mockito.invocation.Invocation;\nimport org.mockito.invocation.InvocationFactory.RealMethodBehavior;\nimport org.mockito.mock.MockCreationSettings;\nimport org.powermock.api.support.SafeExceptionRethrower;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.MockRepository;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\nclass InvocationFactory {\n    \n    Invocation createInvocation(final Object mock, final Method method, final MockCreationSettings settings,\n                                final Object... arguments) {\n        final RealMethodBehavior realMethod = createRealMethod(mock, method, arguments);\n        return Mockito.framework()\n                      .getInvocationFactory()\n                      .createInvocation(mock, settings, method, realMethod, arguments);\n    }\n    \n    private RealMethodBehavior createRealMethod(final Object delegator, final Method method,\n                                                                                         final Object... arguments) {\n        return new RealMethodBehavior() {\n            @Override\n            public Object call() throws Exception {\n                final Class<?> type = Whitebox.getType(delegator);\n                final boolean isFinalSystemClass = type.getName().startsWith(\"java.\") && Modifier.isFinal(type.getModifiers());\n                if (!isFinalSystemClass) {\n                    MockRepository.putAdditionalState(MockGateway.DONT_MOCK_NEXT_CALL, true);\n                }\n                try {\n                    return method.invoke(delegator, arguments);\n                } catch (InvocationTargetException e) {\n                    SafeExceptionRethrower.safeRethrow(e.getCause());\n                }\n                return null;\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockHandlerAdaptor.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.invocation;\n\nimport org.mockito.MockingDetails;\nimport org.mockito.Mockito;\nimport org.mockito.exceptions.base.MockitoAssertionError;\nimport org.mockito.exceptions.misusing.NotAMockException;\nimport org.mockito.invocation.Invocation;\nimport org.mockito.invocation.MockHandler;\nimport org.mockito.mock.MockCreationSettings;\nimport org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError;\nimport org.powermock.core.MockRepository;\n\nimport java.lang.reflect.Method;\n\n/**\n * The class provides a access to method and data of  {@link org.mockito.invocation.MockHandler} from the given mock instance.\n */\npublic class MockHandlerAdaptor<T> {\n    private final T mock;\n    private final InvocationFactory invocationFactory;\n    private final MockingDetails mockingDetails;\n    \n    MockHandlerAdaptor(final T mock) {\n        this.mock = mock;\n        this.invocationFactory = new InvocationFactory();\n        this.mockingDetails = Mockito.mockingDetails(mock);\n    }\n    \n    public Object getMock() {\n        return mock;\n    }\n    \n    public MockCreationSettings<?> getMockSettings() {\n        return mockingDetails.getMockCreationSettings();\n    }\n    \n    private MockHandler getMockHandler() {\n        return mockingDetails.getMockHandler();\n    }\n    \n    Object performIntercept(final Object mock, final Method method, Object[] arguments) throws Throwable {\n        \n        Invocation invocation = createInvocation(mock, method, arguments);\n        \n        try {\n            return getMockHandler().handle(invocation);\n        } catch (NotAMockException e) {\n            if (invocation.getMock()\n                          .getClass()\n                          .getName()\n                          .startsWith(\"java.\") && MockRepository.getInstanceMethodInvocationControl(invocation.getMock()) != null) {\n                return invocation.callRealMethod();\n            } else {\n                throw e;\n            }\n        } catch (MockitoAssertionError e) {\n            InvocationControlAssertionError.updateErrorMessageForMethodInvocation(e);\n            throw e;\n        }\n    }\n    \n    private Invocation createInvocation(final Object mock, final Method method, final Object[] arguments) {\n        return invocationFactory.createInvocation(mock, method, getMockHandler().getMockSettings(), arguments);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockitoMethodInvocationControl.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.invocation;\n\nimport org.mockito.Mockito;\nimport org.mockito.exceptions.base.MockitoAssertionError;\nimport org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError;\nimport org.powermock.api.mockito.internal.stubbing.MockitoRealMethodInvocation;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.spi.MethodInvocationControl;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * A Mockito implementation of the {@link MethodInvocationControl} interface.\n */\npublic class MockitoMethodInvocationControl<T> implements MethodInvocationControl {\n    \n    private final Set<Method> mockedMethods;\n    private final Object delegator;\n    private final MockHandlerAdaptor<T> mockHandlerAdaptor;\n    \n    /**\n     * Creates a new instance with a delegator. This delegator may be\n     * {@code null} (if it is then no calls will be forwarded to this\n     * instance). If a delegator exists (i.e. not null) all non-mocked calls\n     * will be delegated to that instance.\n     *\n     * @param delegator     If the user spies on an instance the original instance must be\n     *                      injected here.\n     * @param mockInstance  The actual mock instance. May be {@code null}. Even\n     *                      though the mock instance may not be used it's needed to keep a\n     *                      reference to this object otherwise it may be garbage collected\n     *                      in some situations. For example when mocking static methods we\n     *                      don't return the mock object and thus it will be garbage\n     *                      collected (and thus the finalize method will be invoked which\n     *                      will be caught by the proxy and the test will fail because we\n     *                      haven't setup expectations for this method) because then that\n     *                      object has no reference. In order to avoid this we keep a\n     *                      reference to this instance here.\n     * @param methodsToMock The methods that are mocked for this instance. If\n     *                      {@code methodsToMock} is null or empty, all methods for\n     *                      the {@code invocationHandler} are considered to be\n     */\n    public MockitoMethodInvocationControl(Object delegator, T mockInstance, Method... methodsToMock) {\n        this.mockHandlerAdaptor = new MockHandlerAdaptor<T>(mockInstance);\n        this.mockedMethods = toSet(methodsToMock);\n        this.delegator = delegator;\n    }\n    \n    @Override\n    public boolean isMocked(Method method) {\n        return mockedMethods == null || (mockedMethods.contains(method));\n    }\n    \n    @Override\n    public Object invoke(final Object mock, final Method method, final Object[] arguments) throws Throwable {\n        /*\n           * If we come here and it means that the class has been modified by\n           * PowerMock. If this handler has a delegator (i.e. is in spy mode in\n           * the current implementation) and it has been caught by the Mockito\n           * proxy before our MockGateway we need to know if the method is private\n           * or not. Because if the previously described preconditions are met and\n           * the method is not private it means that Mockito has already processed\n           * the method invocation and we should NOT delegate the call to Mockito\n           * again (thus we return proceed). If we would do that Mockito will\n           * receive multiple method invocations to proxy for each method\n           * invocation. For privately spied methods Mockito haven't received the\n           * invocation and thus we should delegate the call to the Mockito proxy.\n           */\n        final Object returnValue;\n        if (isCanBeHandledByMockito(method) && hasBeenCaughtByMockitoProxy()) {\n            returnValue = MockGateway.PROCEED;\n        } else {\n            if (mock instanceof Class) {\n                returnValue = mockHandlerAdaptor.performIntercept(mockHandlerAdaptor.getMockSettings().getTypeToMock(), method, arguments);\n            } else {\n                returnValue = mockHandlerAdaptor.performIntercept(mock, method, arguments);\n            }\n            if (returnValue == null) {\n                return MockGateway.SUPPRESS;\n            }\n        }\n        return returnValue;\n    }\n    \n    private boolean isCanBeHandledByMockito(final Method method) {\n        final int modifiers = method.getModifiers();\n        return hasDelegator() && !Modifier.isPrivate(modifiers) && !Modifier.isFinal(modifiers) && !Modifier.isStatic(modifiers);\n    }\n    \n    private boolean hasBeenCaughtByMockitoProxy() {\n        return MockitoRealMethodInvocation.isHandledByMockito();\n    }\n    \n    @Override\n    public Object replay(Object... mocks) {\n        throw new IllegalStateException(\"Internal error: No such thing as replay exists in Mockito.\");\n    }\n    \n    @Override\n    public Object reset(Object... mocks) {\n        throw new IllegalStateException(\"Internal error: No such thing as reset exists in Mockito.\");\n    }\n    \n    public void verifyNoMoreInteractions() {\n        try {\n            Mockito.verifyNoMoreInteractions(getMockHandlerAdaptor().getMock());\n        } catch (MockitoAssertionError e) {\n            //TODO replace this dirty hack\n            InvocationControlAssertionError.updateErrorMessageForVerifyNoMoreInteractions(e);\n            throw e;\n        } catch (Exception e) {\n            throw new RuntimeException(\"PowerMock internal error\", e);\n        }\n    }\n    \n    private Set<Method> toSet(Method... methods) {\n        return methods == null ? null : new HashSet<Method>(Arrays.asList(methods));\n    }\n    \n    private boolean hasDelegator() {\n        return delegator != null;\n    }\n    \n    public MockHandlerAdaptor<T> getMockHandlerAdaptor() {\n        return mockHandlerAdaptor;\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockmaker/MockMakerLoader.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.mockmaker;\n\nimport org.mockito.Mockito;\nimport org.mockito.plugins.MockMaker;\nimport org.powermock.configuration.MockitoConfiguration;\n\nclass MockMakerLoader {\n    MockMaker load(final MockitoConfiguration mockitoConfiguration) {\n        \n        ClassLoader loader = Thread.currentThread().getContextClassLoader();\n        if (loader == null) {\n            loader = ClassLoader.getSystemClassLoader();\n        }\n        \n        String mockMakerClassName = mockitoConfiguration.getMockMakerClass();\n        \n        try {\n            return doLoad(loader, mockMakerClassName);\n        } catch (Exception e) {\n            throw new IllegalStateException(\"Failed to load MockMaker implementation: \" + mockMakerClassName, e);\n        }\n    }\n    \n    private MockMaker doLoad(final ClassLoader loader, final String mockMakerClassName)\n        throws ClassNotFoundException, InstantiationException, IllegalAccessException {\n        if (mockMakerClassName == null) {\n            return Mockito.framework().getPlugins().getDefaultPlugin(MockMaker.class);\n        } else if (\"mock-maker-inline\".equals(mockMakerClassName)) {\n            return Mockito.framework().getPlugins().getInlineMockMaker();\n        } else {\n            Class<?> mockMakerClass = loader.loadClass(mockMakerClassName);\n            Object mockMaker = mockMakerClass.newInstance();\n            return MockMaker.class.cast(mockMaker);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockmaker/PowerMockMaker.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.mockmaker;\n\nimport org.mockito.Mockito;\nimport org.mockito.invocation.Invocation;\nimport org.mockito.invocation.InvocationContainer;\nimport org.mockito.invocation.MockHandler;\nimport org.mockito.mock.MockCreationSettings;\nimport org.mockito.plugins.MockMaker;\nimport org.powermock.api.mockito.invocation.MockitoMethodInvocationControl;\nimport org.powermock.configuration.GlobalConfiguration;\nimport org.powermock.core.MockRepository;\n\n/**\n * A PowerMock implementation of the MockMaker.\n */\npublic class PowerMockMaker implements MockMaker {\n    private final MockMaker mockMaker;\n    \n    public PowerMockMaker() {\n        mockMaker = new MockMakerLoader().load(GlobalConfiguration.mockitoConfiguration());\n    }\n    \n    @Override\n    public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler){\n        return mockMaker.createMock(settings, handler);\n    }\n    \n    @Override\n    public MockHandler getHandler(Object mock) {\n        if (mock instanceof Class) {\n            return staticMockHandler((Class) mock);\n        } else {\n            return instanceMockHandler(mock);\n        }\n    }\n    \n    private MockHandler instanceMockHandler(final Object mock) {\n        return mockMaker.getHandler(getRealMock(mock));\n    }\n    \n    private Object getRealMock(final Object mock) {\n        final MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(mock);\n        final Object realMock;\n        if (invocationControl == null){\n            realMock = mock;\n        }else{\n            realMock = invocationControl.getMockHandlerAdaptor().getMock();\n\n        }\n        return realMock;\n    }\n    \n    private MockHandler staticMockHandler(final Class mock) {\n        return new StaticMockHandler(createStaticMockSettings(mock));\n    }\n    \n    @Override\n    public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {\n        mockMaker.resetMock(mock, newHandler, settings);\n    }\n    \n    @Override\n    public TypeMockability isTypeMockable(Class<?> type) {\n        return mockMaker.isTypeMockable(type);\n    }\n    \n    MockMaker getMockMaker() {\n        return mockMaker;\n    }\n    \n    @SuppressWarnings(\"unchecked\")\n    private MockCreationSettings<Class> createStaticMockSettings(final Class mock) {\n        return Mockito.withSettings()\n                      .name(mock.getName())\n                      .build((Class<Class>) mock);\n    }\n    \n    private static class StaticMockHandler implements MockHandler<Class> {\n        private final MockCreationSettings<Class> mockSettings;\n        \n        private StaticMockHandler(final MockCreationSettings<Class> mockSettings) {\n            this.mockSettings = mockSettings;\n        }\n        \n        @Override\n        public MockCreationSettings<Class> getMockSettings() {\n            return mockSettings;\n        }\n        \n        @Override\n        public InvocationContainer getInvocationContainer() {\n            return null;\n        }\n        \n        @Override\n        public Object handle(Invocation invocation) throws Throwable {\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockpolicies/Slf4jMockPolicy.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.mockpolicies;\n\nimport org.mockito.Mockito;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.mockpolicies.support.LogPolicySupport;\n\nimport java.lang.reflect.Method;\n\n/**\n * Sfl4j mock policy that injects a Mockito-created mock to be returned on calls to getLogger factory methods.\n * The implementation returns a single mock instance per thread but it doesn't return a different mock instance based\n * on the actual value passed to getLogger. This limitation is acceptable in most real uses cases.\n * <p/>\n * Tests that want to do verifications on the mocked logger can do so by getting the mocked instance as production code\n * does: {@code org.slf4j.LoggerFactory.getLogger(Class)}. However, it is critical that the mocked logger is\n * reset after each test in order to avoid crosstalk between test cases.\n * <p/>\n *\n * @author Alexandre Normand <alexandre.normand@gmail.com>\n */\npublic class Slf4jMockPolicy implements PowerMockPolicy {\n\n    private static final String LOGGER_FACTORY_CLASS_NAME = \"org.slf4j.LoggerFactory\";\n    private static final String LOGGER_FACTORY_METHOD_NAME = \"getLogger\";\n    private static final String FRAMEWORK_NAME = \"sfl4j\";\n    private static final String LOGGER_CLASS_NAME = \"org.slf4j.Logger\";\n\n    private static ThreadLocal<Object> threadLogger = new ThreadLocal<Object>();\n\n    @Override\n    public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings mockPolicyClassLoadingSettings) {\n        mockPolicyClassLoadingSettings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(\n                LOGGER_FACTORY_CLASS_NAME,\n                \"org.apache.log4j.Appender\",\n                \"org.apache.log4j.xml.DOMConfigurator\");\n    }\n\n    @Override\n    public void applyInterceptionPolicy(MockPolicyInterceptionSettings mockPolicyInterceptionSettings) {\n        LogPolicySupport logPolicySupport = new LogPolicySupport();\n\n        Method[] loggerFactoryMethods = logPolicySupport.getLoggerMethods(LOGGER_FACTORY_CLASS_NAME,\n                LOGGER_FACTORY_METHOD_NAME, FRAMEWORK_NAME);\n\n        initializeMockForThread(logPolicySupport);\n\n        for (Method loggerFactoryMethod : loggerFactoryMethods) {\n            mockPolicyInterceptionSettings.stubMethod(loggerFactoryMethod, threadLogger.get());\n        }\n    }\n\n    private void initializeMockForThread(LogPolicySupport logPolicySupport) {\n        Class<?> loggerClass = getLoggerClass(logPolicySupport);\n\n        if (threadLogger.get() == null) {\n            /*\n             * When mocking with Mockito we need to change the context CL to the same CL that is loading Mockito\n             * otherwise the Mockito plugin mechanism will load the PowerMockMaker from the wrong classloader.\n             */\n            final ClassLoader originalCl = Thread.currentThread().getContextClassLoader();\n            final ClassLoader classLoader = Mockito.class.getClassLoader();\n            Thread.currentThread().setContextClassLoader(classLoader);\n            final Object mock;\n            try {\n                 mock = Mockito.mock(loggerClass);\n            } finally {\n                Thread.currentThread().setContextClassLoader(originalCl);\n            }\n\n            threadLogger.set(mock);\n        }\n    }\n\n    private Class<?> getLoggerClass(LogPolicySupport logPolicySupport) {\n        Class<?> loggerType;\n        try {\n            loggerType = logPolicySupport.getType(LOGGER_CLASS_NAME, FRAMEWORK_NAME);\n        } catch (RuntimeException e) {\n            throw e;\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n\n        return loggerType;\n    }\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/powermocklistener/AnnotationEnabler.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.powermocklistener;\n\n/**\n * Before each test method all fields annotated with {@link org.mockito.Mock} have mock objects created for them\n * and injected to the fields.\n * \n * @deprecated Test Runners uses an annotation enabling listener per default\n *             since version 1.3. You should just remove this listener.\n */\n@Deprecated\npublic class AnnotationEnabler extends org.powermock.api.extension.listener.AnnotationEnabler {\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/ConstructorArgumentsVerification.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.verification;\n\npublic interface ConstructorArgumentsVerification {\n\n    void withArguments(Object argument, Object... additionalArguments) throws Exception;\n\n    void withNoArguments() throws Exception;\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/PrivateMethodVerification.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.verification;\n\nimport java.lang.reflect.Method;\n\npublic interface PrivateMethodVerification {\n\n    /**\n     * Verify calls to private methods without having to specify the method\n     * name. The method will be looked up using the parameter types (if\n     * possible).\n     *\n     * @throws Exception If something unexpected goes wrong.\n     * @deprecated Use {@link #invoke(String, Object...)} instead. Will be remove in PowerMock 3.0\n     */\n    @Deprecated\n    void invoke(Object... arguments) throws Exception;\n\n    /**\n     * Verify calls to the specific method.\n     *\n     * @throws Exception If something unexpected goes wrong.\n     */\n    WithOrWithoutVerifiedArguments invoke(Method method) throws Exception;\n\n    /**\n     * Verify a private method call by specifying the method name of the method\n     * to verify.\n     *\n     * @throws Exception If something unexpected goes wrong.\n     */\n    void invoke(String methodToVerify, Object... arguments) throws Exception;\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/WithOrWithoutVerifiedArguments.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.verification;\n\npublic interface WithOrWithoutVerifiedArguments extends WithVerifiedArguments, WithoutVerifiedArguments {\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/WithVerifiedArguments.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.verification;\n\n\npublic interface WithVerifiedArguments {\n    void withArguments(Object firstArgument, Object... additionalArguments) throws Exception;\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/WithoutVerifiedArguments.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.api.mockito.verification;\n\npublic interface WithoutVerifiedArguments {\n    void withNoArguments() throws Exception;\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/resources/mockito-extensions/org.mockito.plugins.MockMaker",
    "content": "org.powermock.api.mockito.mockmaker.PowerMockMaker"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/main/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider",
    "content": "org.powermock.api.mockito.internal.exceptions.StackTraceCleanerProvider"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/PowerMockMockito2ApiTestSuite.java",
    "content": "package org.powermock.api.mockito;\n\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Suite;\nimport org.powermock.api.mockito.internal.expectation.DefaultMethodExpectationSetupTestCase;\nimport org.powermock.api.mockito.internal.mockcreation.MockCreatorTestCase;\nimport org.powermock.api.mockito.mockmaker.PowerMockMakerTestCase;\n\n\n/*\n * We have to use suite in this case to define order of test and prevent fluky test which\n * are depends on ordering.\n */\n@RunWith(Suite.class)\n@Suite.SuiteClasses({\n                        PowerMockMakerTestCase.class,\n                        MockCreatorTestCase.class,\n                        DefaultMethodExpectationSetupTestCase.class\n})\npublic class PowerMockMockito2ApiTestSuite {\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/expectation/DefaultMethodExpectationSetupTestCase.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.mockito.internal.expectation;\n\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.mockito.exceptions.misusing.MissingMethodInvocationException;\nimport org.powermock.reflect.Whitebox;\n\n/**\n * @author Stanislav Chizhov\n */\npublic class DefaultMethodExpectationSetupTestCase {\n\n    private final CUT object = new CUT();\n\n    @Test(expected = MissingMethodInvocationException.class)\n    public void testWithArguments_Multiple() throws Exception {\n        DefaultMethodExpectationSetup s = new DefaultMethodExpectationSetup(object, object.getClass().getMethod(\"multiple\", Object.class, Object.class, Object.class));\n        Object a1 = new Object();\n        Object a2 = new Object();\n        Object a3 = new Object();\n        s.withArguments(a1, a2, a3);\n    }\n\n    @Test(expected = MissingMethodInvocationException.class)\n    public void testWithArguments_Single() throws Exception {\n        DefaultMethodExpectationSetup s = new DefaultMethodExpectationSetup(object, object.getClass().getMethod(\"single\", Object.class));\n        Object a1 = new Object();\n        s.withArguments(a1);\n    }\n\n    @Test\n    public void testJoin() throws Exception {\n        Object a1 = new Object();\n        Object a2 = new Object();\n        Object a3 = new Object();\n        Object[] res = Whitebox.invokeMethod(DefaultMethodExpectationSetup.class, \"join\", a1, new Object[]{a2, a3});\n\n        Assert.assertArrayEquals(new Object[]{a1, a2, a3}, res);\n    }\n\n    public static class CUT {\n\n        public void multiple(Object a1, Object a2, Object a3) {\n            //Nada\n        }\n\n        public void single(Object a1) {\n            //Nada\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/mockcreation/MockCreatorTestCase.java",
    "content": "package org.powermock.api.mockito.internal.mockcreation;\n\nimport org.junit.Test;\nimport org.mockito.MockSettings;\nimport org.mockito.Mockito;\nimport org.mockito.mock.MockName;\nimport org.powermock.api.mockito.invocation.MockitoMethodInvocationControl;\nimport org.powermock.core.MockRepository;\n\nimport java.util.List;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class MockCreatorTestCase {\n\n\t@Test\n\tpublic void should_return_mock_name_when_settings_have_name() throws NoSuchMethodException, SecurityException {\n        final String definedMockName = \"my-list\";\n        final MockSettings settings = Mockito.withSettings().name(definedMockName);\n        \n        final List<?> result = createMock(settings);\n        \n        final MockName mockName = getMockName(result);\n        \n        assertThat(mockName.toString())\n            .as(\"Mock name is configured\")\n            .isEqualTo(definedMockName);\n    }\n    \n    @Test\n    public void should_return_class_name_when_settings_have_no_name() throws NoSuchMethodException, SecurityException {\n        final MockSettings settings = Mockito.withSettings();\n        \n        final List<?> result = createMock(settings);\n        \n        final MockName mockName = getMockName(result);\n        \n        assertThat(mockName.toString())\n            .as(\"Mock name is configured\")\n            .isEqualTo(\"list\");\n    }\n    \n    private List<?> createMock(final MockSettings settings) throws NoSuchMethodException {\n        return DefaultMockCreator.mock(List.class, false, false, null, settings, List.class.getMethod(\"add\", Object.class));\n    }\n    \n    private MockName getMockName(final List<?> result) {\n        final MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(result);\n        return invocationControl.getMockHandlerAdaptor().getMockSettings().getMockName();\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/mockmaker/PowerMockMakerTestCase.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito.mockmaker;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.JUnitCore;\nimport org.mockito.Mockito;\nimport org.mockito.invocation.Invocation;\nimport org.mockito.invocation.InvocationContainer;\nimport org.mockito.invocation.MockHandler;\nimport org.mockito.mock.MockCreationSettings;\nimport org.mockito.plugins.MockMaker;\nimport org.powermock.api.mockito.ConfigurationTestUtils;\nimport org.powermock.configuration.GlobalConfiguration;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Method;\nimport java.net.URLClassLoader;\nimport java.util.List;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.fail;\nimport static org.junit.Assume.assumeFalse;\n\npublic class PowerMockMakerTestCase {\n    \n    @Test\n    public void should_delegate_calls_to_mock_maker_from_configuration() {\n    \n        final String javaVersion = System.getProperty(\"java.version\");\n        \n        assumeFalse(\"Test failed on JDK9. System class loader does not extends URLClassloader any more.\", javaVersion.startsWith(\"9\"));\n    \n        ClassLoader currentCL = Thread.currentThread().getContextClassLoader();\n    \n        try {\n            ClassLoader classLoader = new URLClassLoader(((URLClassLoader) currentCL).getURLs(), null);\n            Thread.currentThread().setContextClassLoader(classLoader);\n        \n            final Class<?> jUnitCoreClass = classLoader.loadClass(JUnitCore.class.getName());\n            final Class<?> targetTestClass = classLoader.loadClass(TargetTest.class.getName());\n        \n            final Method method = Whitebox.getMethod(jUnitCoreClass, \"runClasses\", Class[].class);\n            Object result = method.invoke(null, new Object[]{new Class[]{targetTestClass}});\n        \n            final List failures = Whitebox.invokeMethod(result, \"getFailures\");\n        \n            assertThat(failures)\n                .withFailMessage(\"Failures description %s\", failures)\n                .isEmpty();\n        \n        } catch (Exception e) {\n            fail(\"Test failed\", e);\n        } finally {\n            Thread.currentThread().setContextClassLoader(currentCL);\n        }\n    \n    \n    }\n    \n    \n    public static class DelegateMockMakerStub implements MockMaker {\n        \n        private final Object mock;\n        \n        public DelegateMockMakerStub() {\n            this.mock = new Object();\n        }\n        \n        @Override\n        public <T> T createMock(final MockCreationSettings<T> settings, final MockHandler handler) {\n            return (T) mock;\n        }\n        \n        @Override\n        public MockHandler getHandler(final Object mock) {\n            return null;\n        }\n        \n        @Override\n        public void resetMock(final Object mock, final MockHandler newHandler, final MockCreationSettings settings) {\n        \n        }\n        \n        @Override\n        public TypeMockability isTypeMockable(final Class<?> type) {\n            return new TypeMockability() {\n                @Override\n                public boolean mockable() {\n                    return true;\n                }\n    \n                @Override\n                public String nonMockableReason() {\n                    return null;\n                }\n            };\n        }\n        \n        private Object getMock() {\n            return mock;\n        }\n    }\n    \n    public static class TargetTest {\n    \n        private ConfigurationTestUtils util;\n    \n        @Before\n        public void setUp() throws Exception {\n            util = new ConfigurationTestUtils();\n            util.copyTemplateToPropertiesFile();\n            GlobalConfiguration.clear();\n        }\n    \n        @After\n        public void tearDown() throws Exception {\n            util.clear();\n            GlobalConfiguration.clear();\n        }\n        \n        @Test\n        public void runTest() {\n            \n            PowerMockMaker powerMockMaker = new PowerMockMaker();\n            Object mock = powerMockMaker.createMock(Mockito.withSettings().build(Object.class), new MockHandler() {\n                @Override\n                public Object handle(final Invocation invocation) throws Throwable {\n                    return null;\n                }\n                \n                @Override\n                public MockCreationSettings getMockSettings() {\n                    return null;\n                }\n                \n                @Override\n                public InvocationContainer getInvocationContainer() {\n                    return null;\n                }\n            });\n            \n            MockMaker mockMaker = powerMockMaker.getMockMaker();\n            \n            assertThat(mockMaker)\n                .as(\"Mock maker instance of configuration\")\n                .isInstanceOf(DelegateMockMakerStub.class);\n            \n            assertThat(((DelegateMockMakerStub) mockMaker).getMock())\n                .as(\"Mock is created by delegated mock maker\")\n                .isSameAs(mock);\n            \n        }\n    }\n}"
  },
  {
    "path": "powermock-api/powermock-api-mockito2/src/test/resources/org/powermock/extensions/configuration.template",
    "content": "mockito.mock-maker-class=org.powermock.api.mockito.mockmaker.PowerMockMakerTestCase$DelegateMockMakerStub"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/ClassLoaderUtil.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support;\n\npublic class ClassLoaderUtil {\n\n    /**\n     * Loads a class with a specific classloader, wraps the\n     * {@link ClassNotFoundException} in a runtime exeception.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> Class<T> loadClass(Class<T> type, ClassLoader classloader) {\n        return loadClass(type.getName(), classloader);\n    }\n\n    /**\n     * Loads a class from the current classloader\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> Class<T> loadClass(String className) {\n        return loadClass(className, ClassLoaderUtil.class.getClassLoader());\n    }\n\n    /**\n     * Check whether a classloader can load the given class.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> boolean hasClass(Class<T> type, ClassLoader classloader) {\n        try {\n            loadClass(type.getName(), classloader);\n            return true;\n        } catch (RuntimeException e) {\n            if(e.getCause() instanceof ClassNotFoundException) {\n                return false;\n            }\n            throw e;\n        }\n    }\n\n    /**\n     * Load a class from a specific classloader\n     */\n    public static <T> Class<T> loadClass(String className, ClassLoader classloader) {\n        if(className == null) {\n            throw new IllegalArgumentException(\"className cannot be null\");\n        }\n\n        if(classloader == null) {\n            throw new IllegalArgumentException(\"classloader cannot be null\");\n        }\n\n        try {\n            return (Class<T>) Class.forName(className, false, classloader);\n        } catch (ClassNotFoundException e) {\n            throw new RuntimeException(e);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/MethodProxy.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\npublic class MethodProxy {\n\t/**\n\t * Add a proxy for this method. Each call to the method will be routed to\n\t * the invocationHandler instead.\n\t */\n\tpublic static void proxy(Method method, InvocationHandler invocationHandler) {\n\t\tassertInvocationHandlerNotNull(invocationHandler);\n\t\tMockRepository.putMethodProxy(method, invocationHandler);\n\t}\n\n\t/**\n\t * Add a proxy for a method declared in class {@code declaringClass}.\n\t * Each call to the method will be routed to the invocationHandler instead.\n\t */\n\tpublic static void proxy(Class<?> declaringClass, String methodName, InvocationHandler invocationHandler) {\n\t\tassertInvocationHandlerNotNull(invocationHandler);\n\t\tif (declaringClass == null) {\n\t\t\tthrow new IllegalArgumentException(\"declaringClass cannot be null\");\n\t\t}\n\t\tif (methodName == null || methodName.length() == 0) {\n\t\t\tthrow new IllegalArgumentException(\"methodName cannot be empty\");\n\t\t}\n\t\tMethod[] methods = Whitebox.getMethods(declaringClass, methodName);\n\t\tif (methods.length == 0) {\n\t\t\tthrow new MethodNotFoundException(String.format(\"Couldn't find a method with name %s in the class hierarchy of %s\", methodName,\n\t\t\t\t\tdeclaringClass.getName()));\n\t\t} else if (methods.length > 1) {\n\t\t\tthrow new TooManyMethodsFoundException(String.format(\"Found %d methods with name %s in the class hierarchy of %s.\", methods.length,\n\t\t\t\t\tmethodName, declaringClass.getName()));\n\t\t}\n\n\t\tMockRepository.putMethodProxy(methods[0], invocationHandler);\n\t}\n\n\tprivate static void assertInvocationHandlerNotNull(InvocationHandler invocationHandler) {\n\t\tif (invocationHandler == null) {\n\t\t\tthrow new IllegalArgumentException(\"invocationHandler cannot be null\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SafeExceptionRethrower.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support;\n\npublic class SafeExceptionRethrower {\n\n\tpublic static void safeRethrow(Throwable t) {\n\t\tSafeExceptionRethrower.<RuntimeException> safeRethrow0(t);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate static <T extends Throwable> void safeRethrow0(Throwable t) throws T {\n\t\tthrow (T) t;\n\t}\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/Stubber.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\n\nimport java.lang.reflect.Method;\n\npublic class Stubber {\n\t/**\n\t * Add a method that should be intercepted and return another value (\n\t * {@code returnObject}) (i.e. the method is stubbed).\n\t */\n\tpublic static void stubMethod(Method method, Object returnObject) {\n\t\tMockRepository.putMethodToStub(method, returnObject);\n\t}\n\n\t/**\n\t * Add a method that should be intercepted and return another value (\n\t * {@code returnObject}) (i.e. the method is stubbed).\n\t */\n\tpublic static void stubMethod(Class<?> declaringClass, String methodName, Object returnObject) {\n\t\tif (declaringClass == null) {\n\t\t\tthrow new IllegalArgumentException(\"declaringClass cannot be null\");\n\t\t}\n\t\tif (methodName == null || methodName.length() == 0) {\n\t\t\tthrow new IllegalArgumentException(\"methodName cannot be empty\");\n\t\t}\n\t\tMethod[] methods = Whitebox.getMethods(declaringClass, methodName);\n\t\tif (methods.length == 0) {\n\t\t\tthrow new MethodNotFoundException(String.format(\"Couldn't find a method with name %s in the class hierarchy of %s\", methodName,\n\t\t\t\t\tdeclaringClass.getName()));\n\t\t} else if (methods.length > 1) {\n\t\t\tthrow new TooManyMethodsFoundException(String.format(\"Found %d methods with name %s in the class hierarchy of %s.\", methods.length,\n\t\t\t\t\tmethodName, declaringClass.getName()));\n\t\t}\n\n\t\tMockRepository.putMethodToStub(methods[0], returnObject);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SuppressCode.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\npublic class SuppressCode {\n\t/**\n\t * Suppress constructor calls on specific constructors only.\n\t */\n\tpublic static synchronized void suppressConstructor(Constructor<?>... constructors) {\n\t\tif (constructors == null) {\n\t\t\tthrow new IllegalArgumentException(\"constructors cannot be null.\");\n\t\t}\n\t\tfor (Constructor<?> constructor : constructors) {\n\t\t\tMockRepository.addConstructorToSuppress(constructor);\n\t\t\t// Also suppress all parent constructors\n\t\t\tClass<?> declaringClass = constructor.getDeclaringClass();\n\t\t\tif (declaringClass != null) {\n\t\t\t\tsuppressConstructor((Class<?>) declaringClass.getSuperclass());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * This method can be used to suppress the code in a specific constructor.\n\t * \n\t * @param clazz\n\t *            The class where the constructor is located.\n\t * @param parameterTypes\n\t *            The parameter types of the constructor to suppress.\n\t */\n\tpublic static synchronized void suppressSpecificConstructor(Class<?> clazz, Class<?>... parameterTypes) {\n\t\tMockRepository.addConstructorToSuppress(Whitebox.getConstructor(clazz, parameterTypes));\n\t}\n\n\t/**\n\t * Suppress all constructors in the given class and it's super classes.\n\t * \n\t * @param classes\n\t *            The classes whose constructors will be suppressed.\n\t */\n\tpublic static synchronized void suppressConstructor(Class<?>... classes) {\n\t\tfor (Class<?> clazz : classes) {\n\t\t\tClass<?> tempClass = clazz;\n\t\t\twhile (tempClass != Object.class) {\n\t\t\t\tsuppressConstructor(tempClass, false);\n\t\t\t\ttempClass = tempClass.getSuperclass();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Suppress all constructors in the given class.\n\t * \n\t * @param clazz\n\t *            The classes whose constructors will be suppressed.\n\t * @param excludePrivateConstructors\n\t *            optionally keep code in private constructors\n\t */\n\tpublic static synchronized void suppressConstructor(Class<?> clazz, boolean excludePrivateConstructors) {\n\t\tConstructor<?>[] ctors = null;\n\n\t\tif (excludePrivateConstructors) {\n\t\t\tctors = clazz.getConstructors();\n\t\t} else {\n\t\t\tctors = clazz.getDeclaredConstructors();\n\t\t}\n\n\t\tfor (Constructor<?> ctor : ctors) {\n\t\t\tMockRepository.addConstructorToSuppress(ctor);\n\t\t}\n\t}\n\n\t/**\n\t * Suppress specific fields. This works on both instance methods and static\n\t * methods. Note that replay and verify are not needed as this is not part\n\t * of a mock behavior.\n\t */\n\tpublic static synchronized void suppressField(Field... fields) {\n\t\tfor (Field field : fields) {\n\t\t\tMockRepository.addFieldToSuppress(field);\n\t\t}\n\t}\n\n\t/**\n\t * Suppress all fields for these classes.\n\t */\n\tpublic static synchronized void suppressField(Class<?>[] classes) {\n\t\tif (classes == null || classes.length == 0) {\n\t\t\tthrow new IllegalArgumentException(\"You must supply at least one class.\");\n\t\t}\n\t\tfor (Class<?> clazz : classes) {\n\t\t\tsuppressField(clazz.getDeclaredFields());\n\t\t}\n\t}\n\n\t/**\n\t * Suppress multiple methods for a class.\n\t * \n\t * @param clazz\n\t *            The class whose methods will be suppressed.\n\t * @param fieldNames\n\t *            The names of the methods that'll be suppressed. If field names\n\t *            are empty, <i>all</i> fields in the supplied class will be\n\t *            suppressed.\n\t */\n\tpublic static synchronized void suppressField(Class<?> clazz, String... fieldNames) {\n\t\tif (fieldNames == null || fieldNames.length == 0) {\n\t\t\tsuppressField(new Class<?>[] { clazz });\n\t\t} else {\n\t\t\tfor (Field field : Whitebox.getFields(clazz, fieldNames)) {\n\t\t\t\tMockRepository.addFieldToSuppress(field);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Suppress specific method calls on all types containing this method. This\n\t * works on both instance methods and static methods. Note that replay and\n\t * verify are not needed as this is not part of a mock behavior.\n\t */\n\tpublic static synchronized void suppressMethod(Method... methods) {\n\t\tfor (Method method : methods) {\n\t\t\tMockRepository.addMethodToSuppress(method);\n\t\t}\n\t}\n\n\t/**\n\t * Suppress all methods for these classes.\n\t * \n\t * @param cls\n\t *            The first class whose methods will be suppressed.\n\t * @param additionalClasses\n\t *            Additional classes whose methods will be suppressed.\n\t */\n\tpublic static synchronized void suppressMethod(Class<?> cls, Class<?>... additionalClasses) {\n\t\tsuppressMethod(cls, false);\n\t\tfor (Class<?> clazz : additionalClasses) {\n\t\t\tsuppressMethod(clazz, false);\n\t\t}\n\t}\n\n\t/**\n\t * Suppress all methods for these classes.\n\t * \n\t * @param classes\n\t *            Classes whose methods will be suppressed.\n\t */\n\tpublic static synchronized void suppressMethod(Class<?>[] classes) {\n\t\tfor (Class<?> clazz : classes) {\n\t\t\tsuppressMethod(clazz, false);\n\t\t}\n\t}\n\n\t/**\n\t * Suppress multiple methods for a class.\n\t * \n\t * @param clazz\n\t *            The class whose methods will be suppressed.\n\t * @param methodName\n\t *            The first method to be suppress in class {@code clazz}.\n\t * @param additionalMethodNames\n\t *            Additional methods to suppress in class {@code clazz}.\n\t */\n\tpublic static synchronized void suppressMethod(Class<?> clazz, String methodName, String... additionalMethodNames) {\n\t\tfor (Method method : Whitebox.getMethods(clazz, methodName)) {\n\t\t\tMockRepository.addMethodToSuppress(method);\n\t\t}\n\t\tif (additionalMethodNames != null && additionalMethodNames.length > 0) {\n\t\t\tfor (Method method : Whitebox.getMethods(clazz, additionalMethodNames)) {\n\t\t\t\tMockRepository.addMethodToSuppress(method);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Suppress multiple methods for a class.\n\t * \n\t * @param clazz\n\t *            The class whose methods will be suppressed.\n\t * @param methodNames\n\t *            Methods to suppress in class {@code clazz}.\n\t */\n\tpublic static synchronized void suppressMethod(Class<?> clazz, String[] methodNames) {\n\t\tfor (Method method : Whitebox.getMethods(clazz, methodNames)) {\n\t\t\tMockRepository.addMethodToSuppress(method);\n\t\t}\n\t}\n\n\t/**\n\t * suSuppress all methods for this class.\n\t * \n\t * @param clazz\n\t *            The class which methods will be suppressed.\n\t * @param excludePrivateMethods\n\t *            optionally not suppress private methods\n\t */\n\tpublic static synchronized void suppressMethod(Class<?> clazz, boolean excludePrivateMethods) {\n\t\tMethod[] methods = null;\n\n\t\tif (excludePrivateMethods) {\n\t\t\tmethods = clazz.getMethods();\n\t\t} else {\n\t\t\tmethods = clazz.getDeclaredMethods();\n\t\t}\n\n\t\tfor (Method method : methods) {\n\t\t\tMockRepository.addMethodToSuppress(method);\n\t\t}\n\t}\n\n\t/**\n\t * Suppress a specific method call. Use this for overloaded methods.\n\t */\n\tpublic static synchronized void suppressMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) {\n\t\tMethod method = null;\n\t\tif (parameterTypes.length > 0) {\n\t\t\tmethod = Whitebox.getMethod(clazz, methodName, parameterTypes);\n\t\t} else {\n\t\t\tmethod = WhiteboxImpl.findMethodOrThrowException(clazz, methodName, parameterTypes);\n\t\t}\n\t\tMockRepository.addMethodToSuppress(method);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberMatcher.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support.membermodification;\n\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyConstructorsFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport org.powermock.tests.utils.impl.ArrayMergerImpl;\n\nimport java.lang.reflect.AccessibleObject;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static java.util.Arrays.asList;\n\n/**\n * Finds members in classes.\n */\npublic class MemberMatcher {\n\n    /**\n     * Get all methods in a class hierarchy of the supplied classes. Both\n     * declared an non-declared (no duplicates).\n     * \n     * @param cls\n     *            The class whose methods to get.\n     * @param additionalClasses\n     *            Additional classes whose methods to get.\n     * @return All methods declared in this class hierarchy.\n     */\n    public static Method[] methodsDeclaredIn(final Class<?> cls, final Class<?>... additionalClasses) {\n        if (cls == null) {\n            throw new IllegalArgumentException(\"You need to supply at least one class.\");\n        }\n        Set<Method> methods = new HashSet<Method>();\n        methods.addAll(asList(WhiteboxImpl.getAllMethods(cls)));\n        for (Class<?> klass : additionalClasses) {\n            methods.addAll(asList(WhiteboxImpl.getAllMethods(klass)));\n        }\n        return methods.toArray(new Method[methods.size()]);\n    }\n\n    /**\n     * Get a method when it cannot be determined by methodName or parameter\n     * types only.\n     * <p>\n     * The method will first try to look for a declared method in the same\n     * class. If the method is not declared in this class it will look for the\n     * method in the super class. This will continue throughout the whole class\n     * hierarchy. If the method is not found an {@link IllegalArgumentException}\n     * is thrown.\n     * \n     * @param declaringClass\n     *            The declaringClass of the class where the method is located.\n     * @param methodName\n     *            The method names.\n     * @param parameterTypes\n     *            All parameter types of the method (may be {@code null}).\n     * @return A {@code java.lang.reflect.Method}.\n     * @throws MethodNotFoundException\n     *             If a method cannot be found in the hierarchy.\n     */\n    public static Method method(Class<?> declaringClass, String methodName, Class<?>... parameterTypes) {\n        final Method method = WhiteboxImpl.findMethod(declaringClass, methodName, parameterTypes);\n        WhiteboxImpl.throwExceptionIfMethodWasNotFound(declaringClass, methodName, method, (Object[]) parameterTypes);\n        return method;\n    }\n\n    /**\n     * Get a method without having to specify the method name.\n     * <p>\n     * The method will first try to look for a declared method in the same\n     * class. If the method is not declared in this class it will look for the\n     * method in the super class. This will continue throughout the whole class\n     * hierarchy. If the method is not found an {@link IllegalArgumentException}\n     * is thrown. Since the method name is not specified an\n     * {@link IllegalArgumentException} is thrown if two or more methods matches\n     * the same parameter types in the same class.\n     * \n     * @param declaringClass\n     *            The declaringClass of the class where the method is located.\n     * @param parameterTypes\n     *            All parameter types of the method (may be {@code null}).\n     * @return A {@code java.lang.reflect.Method}.\n     * @throws MethodNotFoundException\n     *             If a method cannot be found in the hierarchy.\n     * @throws TooManyMethodsFoundException\n     *             If several methods were found.\n     */\n    public static Method method(Class<?> declaringClass, Class<?>... parameterTypes) {\n        return Whitebox.getMethod(declaringClass, parameterTypes);\n    }\n\n    /**\n     * Get an array of {@link Method}'s that matches the supplied list of method\n     * names. Both instance and static methods are taken into account.\n     * \n     * @param clazz\n     *            The class that should contain the methods.\n     * @param methodName\n     *            The name of the first method.\n     * @param additionalMethodNames\n     *            Additional names of the methods that will be returned.\n     * @return An array of Method's. May be of length 0 but not\n     *         {@code null}.\n     * @throws MethodNotFoundException\n     *             If no method was found.\n     */\n    public static Method[] methods(Class<?> clazz, String methodName, String... additionalMethodNames) {\n        return Whitebox.getMethods(clazz, merge(methodName, additionalMethodNames));\n    }\n\n    /**\n     * Get an array of {@link Field}'s.\n     * \n     * @param method\n     *            The first field.\n     * @param additionalMethods\n     *            Additional fields\n     * @return An array of {@link Field}.\n     */\n    public static Method[] methods(Method method, Method... additionalMethods) {\n        return merge(method, additionalMethods);\n    }\n\n    /**\n     * Get an array of {@link Method}'s that matches the supplied list of method\n     * names. Both instance and static methods are taken into account.\n     * \n     * @param clazz\n     *            The class that should contain the methods.\n     * @param methodNames\n     *            The names of the methods.\n     * @return An array of Method's. May be of length 0 but not\n     *         {@code null}.\n     * @throws MethodNotFoundException\n     *             If no method was found.\n     */\n    public static Method[] methods(Class<?> clazz, String[] methodNames) {\n        return Whitebox.getMethods(clazz, methodNames);\n    }\n\n    /**\n     * Get a field from a class.\n     * <p>\n     * The method will first try to look for a declared field in the same class.\n     * If the method is not declared in this class it will look for the field in\n     * the super class. This will continue throughout the whole class hierarchy.\n     * If the field is not found an {@link IllegalArgumentException} is thrown.\n     * \n     * @param declaringClass\n     *            The declaringClass of the class where the method is located.\n     * @param fieldName\n     *            The method names.\n     * @return A {@code java.lang.reflect.Field}.\n     * @throws FieldNotFoundException\n     *             If a field cannot be found in the hierarchy.\n     */\n    public static Field field(Class<?> declaringClass, String fieldName) {\n        return Whitebox.getField(declaringClass, fieldName);\n    }\n\n    /**\n     * Get an array of {@link Field}'s that matches the supplied list of field\n     * names.\n     * \n     * @param clazz\n     *            The class that should contain the fields.\n     * @param firstFieldName\n     *            The name of the first field.\n     * @param additionalfieldNames\n     *            The additional names of the fields that will be returned.\n     * @return An array of Field's. May be of length 0 but not {@code null}\n     * \n     */\n    public static Field[] fields(Class<?> clazz, String firstFieldName, String... additionalfieldNames) {\n        return Whitebox.getFields(clazz, merge(firstFieldName, additionalfieldNames));\n    }\n\n    /**\n     * Get all fields in a class hierarchy.\n     * \n     * @param clazz\n     *            The class that should contain the fields.\n     * @return An array of Field's. May be of length 0 but not {@code null}\n     * \n     */\n    public static Field[] fields(Class<?> clazz) {\n        return WhiteboxImpl.getAllFields(clazz);\n    }\n\n    /**\n     * Get an array of {@link Field}'s.\n     * \n     * @param field\n     *            The first field.\n     * @param additionalFields\n     *            Additional fields\n     * @return An array of {@link Field}.\n     */\n    public static Field[] fields(Field field, Field... additionalFields) {\n        return merge(field, additionalFields);\n    }\n\n    /**\n     * Get an array of {@link Field}'s that matches the supplied list of field\n     * names.\n     * \n     * @param clazz\n     *            The class that should contain the fields.\n     * @param fieldNames\n     *            The names of the fields that will be returned.\n     * @return An array of Field's. May be of length 0 but not {@code null}\n     * \n     */\n    public static Field[] fields(Class<?> clazz, String[] fieldNames) {\n        return Whitebox.getFields(clazz, fieldNames);\n    }\n\n    /**\n     * Returns a constructor specified in declaringClass.\n     * \n     * @param declaringClass\n     *            The declaringClass of the class where the constructor is\n     *            located.\n     * @param parameterTypes\n     *            All parameter types of the constructor (may be\n     *            {@code null}).\n     * @return A {@code java.lang.reflect.Constructor}.\n     * @throws ConstructorNotFoundException\n     *             if the constructor cannot be found.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> Constructor<T> constructor(Class<T> declaringClass, Class<?>... parameterTypes) {\n        return (Constructor<T>) WhiteboxImpl.findUniqueConstructorOrThrowException(declaringClass,\n                (Object[]) parameterTypes);\n    }\n\n    /**\n     * Returns any one constructor specified in declaringClass. Is is useful when you only have ONE constructor\n     * declared in {@code declaringClass} but you don't care which parameters it take.\n     * \n     * @param declaringClass\n     *            The declaringClass of the class where the constructor is\n     *            located.\n     * @return A {@code java.lang.reflect.Constructor}.\n     * @throws TooManyConstructorsFoundException\n     *             If more than one constructor was present in\n     *             {@code declaringClass}\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> Constructor<T> constructor(Class<T> declaringClass) {\n        return (Constructor<T>) WhiteboxImpl.findConstructorOrThrowException(declaringClass);\n    }\n\n    /**\n     * Returns the default constructor in {@code declaringClass}\n     *\n     * @param declaringClass\n     *            The declaringClass of the class where the constructor is\n     *            located.\n     * @return A {@code java.lang.reflect.Constructor}.\n     * @throws ConstructorNotFoundException\n     *             If no default constructor was found in  {@code declaringClass}\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> Constructor<T> defaultConstructorIn(Class<T> declaringClass) {\n        return (Constructor<T>) WhiteboxImpl.findDefaultConstructorOrThrowException(declaringClass);\n    }\n\n    /**\n     * Get all constructors in the supplied class(es).\n     * \n     * @param cls\n     *            The class whose constructors to get.\n     * @param additionalClasses\n     *            Additional classes whose constructors to get.\n     * @return All constructors declared in this class.\n     */\n    public static Constructor<?>[] constructorsDeclaredIn(final Class<?> cls, final Class<?>... additionalClasses) {\n        if (cls == null) {\n            throw new IllegalArgumentException(\"You need to supply at least one class.\");\n        }\n        Set<Constructor<?>> constructors = new HashSet<Constructor<?>>();\n        constructors.addAll(asList(WhiteboxImpl.getAllConstructors(cls)));\n        for (Class<?> klass : additionalClasses) {\n            constructors.addAll(asList(WhiteboxImpl.getAllConstructors(klass)));\n        }\n        return constructors.toArray(new Constructor[constructors.size()]);\n    }\n\n    /**\n     * Convenience method to get a constructor from a class.\n     * \n     * @param constructor\n     *            The first constructor.\n     * @param additionalConstructors\n     *            Additional constructors\n     * @return An array of {@code java.lang.reflect.Constructor}.\n     */\n    public static Constructor<?>[] constructors(Constructor<?> constructor, Constructor<?>... additionalConstructors) {\n        return merge(constructor, additionalConstructors);\n    }\n\n    /**\n     * Get all constructors and methods in the supplied class(es).\n     * \n     * @param cls\n     *            The class whose constructors and methods to get.\n     * @param additionalClasses\n     *            Additional classes whose constructors and methods to get.\n     * @return All constructors and methods declared in this class.\n     */\n    public static AccessibleObject[] everythingDeclaredIn(final Class<?> cls, final Class<?>... additionalClasses) {\n        if (cls == null) {\n            throw new IllegalArgumentException(\"You need to supply at least one class.\");\n        }\n        Set<AccessibleObject> accessibleObjects = new HashSet<AccessibleObject>();\n        accessibleObjects.addAll(Collections.unmodifiableCollection(asList(methodsDeclaredIn(cls, additionalClasses))));\n        accessibleObjects.addAll(Collections.unmodifiableCollection(asList(constructorsDeclaredIn(cls,\n                additionalClasses))));\n        return accessibleObjects.toArray(new AccessibleObject[accessibleObjects.size()]);\n    }\n\n    private static String[] merge(String first, String... additional) {\n        return new ArrayMergerImpl().mergeArrays(String.class, new String[] { first }, additional);\n    }\n\n    private static Method[] merge(Method first, Method... additional) {\n        return new ArrayMergerImpl().mergeArrays(Method.class, new Method[] { first }, additional);\n    }\n\n    private static Field[] merge(Field first, Field... additional) {\n        return new ArrayMergerImpl().mergeArrays(Field.class, new Field[] { first }, additional);\n    }\n\n    private static Constructor<?>[] merge(Constructor<?> first, Constructor<?>... additional) {\n        return new ArrayMergerImpl().mergeArrays(Constructor.class, new Constructor<?>[] { first }, additional);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberModifier.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.api.support.membermodification;\n\nimport org.powermock.api.support.SuppressCode;\nimport org.powermock.api.support.membermodification.strategy.MethodReplaceStrategy;\nimport org.powermock.api.support.membermodification.strategy.MethodStubStrategy;\nimport org.powermock.api.support.membermodification.strategy.impl.MethodReplaceStrategyImpl;\nimport org.powermock.api.support.membermodification.strategy.impl.MethodStubStrategyImpl;\n\nimport java.lang.reflect.AccessibleObject;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\n/**\n * Contains various utilities for modifying members of classes such as\n * constructors, fields and methods. Modifying means e.g. changing return value\n * of method invocations or suppressing a constructor.\n */\npublic class MemberModifier extends MemberMatcher {\n\n    /**\n     * Suppress a specific method. This works on both instance methods and\n     * static methods.\n     */\n    public static void suppress(Method method) {\n        SuppressCode.suppressMethod(method);\n    }\n\n    /**\n     * Suppress multiple methods. This works on both instance methods and static\n     * methods.\n     */\n    public static void suppress(Method[] methods) {\n        SuppressCode.suppressMethod(methods);\n    }\n\n    /**\n     * Suppress a constructor.\n     */\n    public static void suppress(Constructor<?> constructor) {\n        SuppressCode.suppressConstructor(constructor);\n    }\n\n    /**\n     * Suppress multiple constructors.\n     */\n    public static void suppress(Constructor<?>[] constructors) {\n        SuppressCode.suppressConstructor(constructors);\n    }\n\n    /**\n     * Suppress a field.\n     */\n    public static void suppress(Field field) {\n        SuppressCode.suppressField(field);\n    }\n\n    /**\n     * Suppress multiple fields.\n     */\n    public static void suppress(Field[] fields) {\n        SuppressCode.suppressField(fields);\n    }\n\n    /**\n     * Suppress an array of accessible objects.\n     */\n    public static void suppress(AccessibleObject[] accessibleObjects) {\n        if (accessibleObjects == null) {\n            throw new IllegalArgumentException(\"accessibleObjects cannot be null\");\n        }\n\n        for (AccessibleObject accessibleObject : accessibleObjects) {\n            if (accessibleObject instanceof Constructor<?>) {\n                SuppressCode.suppressConstructor((Constructor<?>) accessibleObject);\n            } else if (accessibleObject instanceof Field) {\n                SuppressCode.suppressField((Field) accessibleObject);\n            } else if (accessibleObject instanceof Method) {\n                SuppressCode.suppressMethod((Method) accessibleObject);\n            }\n        }\n    }\n\n    /**\n     * Add a method that should be intercepted and return another value (i.e.\n     * the method is stubbed).\n     */\n    public static <T> MethodStubStrategy<T> stub(Method method) {\n        return new MethodStubStrategyImpl<T>(method);\n    }\n\n    /**\n     * Replace a method invocation.\n     */\n    public static MethodReplaceStrategy replace(Method method) {\n        return new MethodReplaceStrategyImpl(method);\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/ClassReplaceStrategy.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support.membermodification.strategy;\n\n/**\n * Specifies the replace strategy for a class.\n */\npublic interface ClassReplaceStrategy {\n\n\t/**\n\t * Replaces all method invocations on class specified class with method\n\t * invocation to {@code cls}. Also replaces all constructor\n\t * invocations. You can see this as duck typing.\n\t * \n\t * @param cls\n\t *            The class that will replace the other class.\n\t */\n\tvoid with(Class<?> cls);\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/MethodReplaceStrategy.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support.membermodification.strategy;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\n/**\n * Specifies the replace strategy for a method.\n */\npublic interface MethodReplaceStrategy {\n\n\t/**\n\t * Replaces the method invocation with this method.\n\t * <p>\n\t * Note that both methods needs to be static.\n\t * \n\t * @param method\n\t *            The method call will be replaced by this method instead. Needs\n\t *            to be static.\n\t */\n\tvoid with(Method method);\n\n\t/**\n\t * Replaces the method invocation with an invocation handler\n\t * \n\t * @param invocationHandler\n\t *            The invocation handler to replace the method call with.\n\t */\n\tvoid with(InvocationHandler invocationHandler);\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/MethodStubStrategy.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support.membermodification.strategy;\n\n/**\n * Specifies the return value when stubbing a method.\n */\npublic interface MethodStubStrategy<T> {\n\n\t/**\n\t * Stubs the method to return the specified returnValue.\n\t * \n\t * @param returnValue\n\t *            The value that will be returned.\n\t * @deprecated Since version 1.4.1, use {@link #toReturn(Object)} instead.\n\t */\n\t@Deprecated\n\tvoid andReturn(T returnValue);\n\n\t/**\n\t * Stubs the method to return the specified returnValue.\n     *\n\t * @param returnValue\n\t *            The value that will be returned.\n\t */\n\tvoid toReturn(T returnValue);\n\n\t/**\n\t * Stubs the method to throw the specified throwable.\n\t * \n\t * @param throwable\n\t *            the throwable\n\t */\n\tvoid toThrow(Throwable throwable);\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodReplaceStrategyImpl.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support.membermodification.strategy.impl;\n\nimport org.powermock.api.support.MethodProxy;\nimport org.powermock.api.support.membermodification.strategy.MethodReplaceStrategy;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\npublic class MethodReplaceStrategyImpl implements MethodReplaceStrategy {\n\n    private final Method method;\n\n    public MethodReplaceStrategyImpl(Method method) {\n        if (method == null) {\n            throw new IllegalArgumentException(\"Cannot replace a null method.\");\n        }\n        this.method = method;\n    }\n\n    @Override\n    public void with(Method method) {\n        if (method == null) {\n            throw new IllegalArgumentException(\"A metod cannot be replaced with null.\");\n        }\n        if (!Modifier.isStatic(this.method.getModifiers())) {\n            throw new IllegalArgumentException(String.format(\"Replace requires static methods, '%s' is not static\", this.method));\n        } else if (!Modifier.isStatic(method.getModifiers())) {\n            throw new IllegalArgumentException(String.format(\"Replace requires static methods, '%s' is not static\", method));\n        } else  if(!this.method.getReturnType().isAssignableFrom(method.getReturnType())) {\n            throw new IllegalArgumentException(String.format(\"The replacing method (%s) needs to return %s and not %s.\",method.toString(), this.method.getReturnType().getName(), method.getReturnType().getName()));\n        } else if(!WhiteboxImpl.checkIfParameterTypesAreSame(this.method.isVarArgs(),this.method.getParameterTypes(), method.getParameterTypes())) {\n            throw new IllegalArgumentException(String.format(\"The replacing method, \\\"%s\\\", needs to have the same number of parameters of the same type as as method \\\"%s\\\".\",method.toString(),this.method.toString()));\n        } else {\n            MethodProxy.proxy(this.method, new MethodInvocationHandler(method));\n        }\n    }\n\n    @Override\n    public void with(InvocationHandler invocationHandler) {\n        if (invocationHandler == null) {\n            throw new IllegalArgumentException(\"Invocation handler cannot be null\");\n        }\n        MethodProxy.proxy(method, invocationHandler);\n    }\n\n    private final class MethodInvocationHandler implements InvocationHandler {\n        private final Method methodDelegator;\n\n        public MethodInvocationHandler(Method methodDelegator) {\n            this.methodDelegator = methodDelegator;\n        }\n\n        @Override\n        public Object invoke(Object object, Method invokingMethod, Object[] arguments) throws Throwable {\n            return methodDelegator.invoke(object, arguments);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodStubStrategyImpl.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.api.support.membermodification.strategy.impl;\n\nimport org.powermock.api.support.MethodProxy;\nimport org.powermock.api.support.Stubber;\nimport org.powermock.api.support.membermodification.strategy.MethodStubStrategy;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\npublic class MethodStubStrategyImpl<T> implements MethodStubStrategy<T> {\n\n\tprivate final Method method;\n\n\tpublic MethodStubStrategyImpl(Method method) {\n\t\tif (method == null) {\n\t\t\tthrow new IllegalArgumentException(\"Method to stub cannot be null.\");\n\t\t}\n\t\tthis.method = method;\n\t}\n\n\t@Deprecated\n\t@Override\n\tpublic void andReturn(T returnValue) {\n\t\ttoReturn(returnValue);\n\t}\n\n\t@Override\n\tpublic void toThrow(final Throwable throwable) {\n\t\tInvocationHandler throwingInvocationHandler = new InvocationHandler() {\n\n\t\t\t@Override\n\t\t\tpublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n\t\t\t\tthrow throwable;\n\t\t\t}\n\t\t};\n\t\tMethodProxy.proxy(method, throwingInvocationHandler);\n\t}\n\n\t@Override\n\tpublic void toReturn(T returnValue) {\n\t\tStubber.stubMethod(method, returnValue);\n\t}\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/AbstractClassloaderExecutor.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.classloading;\n\nimport org.powermock.api.support.ClassLoaderUtil;\nimport org.powermock.api.support.SafeExceptionRethrower;\nimport org.powermock.classloading.spi.DeepClonerSPI;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\nimport java.util.concurrent.Callable;\n\npublic abstract class AbstractClassloaderExecutor implements ClassloaderExecutor {\n    @Override\n    @SuppressWarnings(\"unchecked\")\n    public <T> T execute(Callable<T> callable) {\n        assertArgumentNotNull(callable, \"callable\");\n        return (T) execute(callable, Whitebox.getMethod(callable.getClass(), \"call\"));\n    }\n    \n    @Override\n    public void execute(Runnable runnable) {\n        assertArgumentNotNull(runnable, \"runnable\");\n        execute(runnable, Whitebox.getMethod(runnable.getClass(), \"run\"));\n    }\n    \n    private void assertArgumentNotNull(Object object, String argumentName) {\n        if (object == null) {\n            throw new IllegalArgumentException(argumentName + \" cannot be null.\");\n        }\n    }\n    \n    protected abstract Object execute(Object instance, Method method, Object... arguments);\n    \n    Object executeWithClassLoader(Object instance, Method method, ClassLoader classloader, Object[] arguments) {\n        final DeepClonerSPI deepCloner = createDeepCloner(classloader);\n        final Object objectLoadedWithClassloader = deepCloner.clone(instance);\n        final Object[] argumentsLoadedByClassLoader = cloneArguments(arguments, deepCloner);\n        \n        return invokeWithClassLoader(classloader, method, objectLoadedWithClassloader, argumentsLoadedByClassLoader);\n    }\n    \n    private Object invokeWithClassLoader(final ClassLoader classloader, final Method method, final Object objectLoadedWithClassloader,\n                                         final Object[] argumentsLoadedByClassLoader) {\n        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n        try {\n            Thread.currentThread().setContextClassLoader(classloader);\n            Object result = getResult(method, objectLoadedWithClassloader, argumentsLoadedByClassLoader);\n            return cloneResult(result);\n        } finally {\n            Thread.currentThread().setContextClassLoader(classLoader);\n        }\n    }\n    \n    private Object cloneResult(Object result) {return result == null ? null : createDeepCloner(getClass().getClassLoader()).clone(result);}\n    \n    private Object getResult(Method method, Object objectLoadedWithClassloader, Object[] argumentsLoadedByClassLoader) {\n        Object result = null;\n        try {\n            result = Whitebox.invokeMethod(objectLoadedWithClassloader, method.getName(), argumentsLoadedByClassLoader);\n        } catch (Exception e) {\n            SafeExceptionRethrower.safeRethrow(e);\n        }\n        return result;\n    }\n    \n    private Object[] cloneArguments(Object[] arguments, DeepClonerSPI deepCloner) {\n        final Object[] argumentsLoadedByClassLoader = new Object[arguments.length];\n        for (int i = 0; i < arguments.length; i++) {\n            final Object argument = arguments[i];\n            argumentsLoadedByClassLoader[i] = deepCloner.clone(argument);\n        }\n        return argumentsLoadedByClassLoader;\n    }\n    \n    private DeepClonerSPI createDeepCloner(ClassLoader classLoader) {\n        final Class<DeepClonerSPI> deepClonerClass = ClassLoaderUtil.loadClass(\"org.powermock.classloading.DeepCloner\");\n        ClassLoader currentCL = Thread.currentThread().getContextClassLoader();\n        try {\n            Thread.currentThread().setContextClassLoader(deepClonerClass.getClass().getClassLoader());\n            return doCreateDeepCloner(classLoader, deepClonerClass);\n        } finally {\n            Thread.currentThread().setContextClassLoader(currentCL);\n        }\n    }\n    \n    private DeepClonerSPI doCreateDeepCloner(final ClassLoader classLoader, final Class<DeepClonerSPI> deepClonerClass) {\n        final Constructor<DeepClonerSPI> constructor = Whitebox.getConstructor(deepClonerClass, ClassLoader.class);\n        try {\n            return constructor.newInstance(classLoader);\n        } catch (Exception e) {\n            throw new RuntimeException(\"Failed to instantiate DeepCloner. The DeepCloner implementation must have a one-arg constructor taking a Classloader as parameter.\", e);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/ClassloaderExecutor.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.classloading;\n\nimport org.powermock.classloading.spi.DeepClonerSPI;\n\nimport java.util.concurrent.Callable;\n\n/**\n * A ClassLoaderExecutor can run any code in any classloader. E.g. assume you have a classloader\n * called myClassloader and you want to execute a (void) method called myMethod in myObject using this CL:\n * <pre>\n *     SingleClassloaderExecutor cle = new SingleClassloaderExecutor(myClassloader);\n *     cle.execute(new Runnable() {\n *          public void run() {\n *             myObject.myMethod();\n *          }\n *     });\n * </pre>\n *\n * What happens is that the entire object graph of myObject is deep-cloned into the {@code myClassloader} classloader\n * and then the {@code myObject.myMethod()} is executed.\n * <p>\n * You can also execute methods that return something:\n * <pre>\n *     SingleClassloaderExecutor cle = new SingleClassloaderExecutor(myClassloader);\n *     MyResult result = cle.execute(new Callable<MyResult>() {\n *          public MyResult call() throws Exception {\n *             return myObject.myMethod();\n *          }\n *     });\n * </pre>\n * Here we imagine that {@code myObject.myMethod()} returns an object of type {@code MyResult}. Again the entire\n * state will be deep-cloned to  {@code myClassloader} and then the {@code myObject.myMethod()} is executed.\n * The result of the method call is deep-cloned back into the original classloader (the one that made the call to\n * {@code cle.execute(..)}) and is ready for use.\n * </p>\n * <p>\n * Note that the SingleClassloaderExecutor requires a deep cloner implementing the {@link DeepClonerSPI} present in the class-path.\n * </p>\n */\npublic interface ClassloaderExecutor {\n\n    <T> T execute(Callable<T> callable);\n\n    void execute(Runnable runnable);\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/SingleClassloaderExecutor.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.classloading;\n\nimport org.powermock.classloading.spi.DoNotClone;\n\nimport java.lang.reflect.Method;\n\npublic class SingleClassloaderExecutor extends AbstractClassloaderExecutor {\n\n\t@DoNotClone\n\tprivate final ClassLoader classloader;\n\n\tpublic SingleClassloaderExecutor(ClassLoader classloader) {\n\t\tthis.classloader = classloader;\n\t}\n\n    @Override\n    protected Object execute(Object instance, Method method, Object... arguments) {\n        return executeWithClassLoader(instance, method, classloader, arguments);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/spi/DeepClonerSPI.java",
    "content": "package org.powermock.classloading.spi;\n\n/**\n * A deep-cloner must implement this interface.\n */\npublic interface DeepClonerSPI {\n    <T> T clone(T objectToClone);\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/spi/DoNotClone.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.classloading.spi;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * Fields annotated with this annotation are not allowed to be cloned by a Deep Cloner implementation.\n */\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.FIELD)\n@Inherited\npublic @interface DoNotClone {\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-objenesis/src/main/java/org/powermock/classloading/DeepCloner.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.classloading;\n\nimport org.powermock.api.support.ClassLoaderUtil;\nimport org.powermock.api.support.SafeExceptionRethrower;\nimport org.powermock.classloading.spi.DeepClonerSPI;\nimport org.powermock.classloading.spi.DoNotClone;\nimport org.powermock.core.ListMap;\nimport org.powermock.reflect.Whitebox;\nimport sun.misc.Unsafe;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.Map;\n\n/**\n * <p>\n * The purpose of the deep cloner is to create a deep clone of an object. An\n * object can also be cloned to a different class-loader.\n * </p>\n */\npublic class DeepCloner implements DeepClonerSPI {\n\n\tprivate final ClassLoader targetCL;\n\tprivate final Map<Object, Object> referenceMap = new ListMap<Object, Object>();\n\tprivate final Class<DoNotClone> doNotClone;\n\n\t/**\n\t * Clone using the supplied ClassLoader.\n     * @param classLoader - the classloader to loaded cloned classes.\n\t */\n\tpublic DeepCloner(ClassLoader classLoader) {\n\t\tthis.targetCL = classLoader;\n\t\tdoNotClone = getDoNotClone(targetCL);\n\t}\n\n\t/**\n\t * Clone using the current ContextClassLoader.\n\t */\n\tpublic DeepCloner() {\n\t\tthis(Thread.currentThread().getContextClassLoader());\n\t}\n\n\tprivate Class<DoNotClone> getDoNotClone(ClassLoader targetCL) {\n\t\treturn ClassLoaderUtil.loadClass(DoNotClone.class, targetCL);\n\t}\n\n\t/**\n\t * Clones an object.\n\t *\n     * @param objectToClone the object to clone.\n\t * @return A deep clone of the object to clone.\n\t */\n\t@Override\n\tpublic <T> T clone(T objectToClone) {\n\t\treturn clone(objectToClone, true);\n\t}\n\n\t/**\n\t *\n     * @param objectToClone the object to clone\n\t * @param includeStandardJavaType\n\t *            {@code true} also clones standard java types (using\n\t *            simple serialization), {@code false} simply reference to\n\t *            these objects (will be same instance).\n\t * @return A deep clone of the object to clone.\n\t */\n\tpublic <T> T clone(T objectToClone, boolean includeStandardJavaType) {\n\t\tassertObjectNotNull(objectToClone);\n\t\treturn performClone(ClassLoaderUtil.loadClass(getType(objectToClone), targetCL), objectToClone,\n\t\t\t\tincludeStandardJavaType);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate static <T> Class<T> getType(T object) {\n\t\tif (object == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn (Class<T>) (object instanceof Class ? object : object.getClass());\n\t}\n\n\tprivate static boolean isClass(Object object) {\n\t\tif (object == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn object instanceof Class<?>;\n\t}\n\n\tprivate static void assertObjectNotNull(Object object) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(\"Object to clone cannot be null\");\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate <T> T performClone(Class<T> targetClass, Object source, boolean shouldCloneStandardJavaTypes) {\n\t\tObject target = null;\n\t\tif (targetClass.isArray() && !isClass(source)) {\n\t\t\treturn (T) instantiateArray(targetCL, targetClass, source, shouldCloneStandardJavaTypes);\n\t\t} else if (isJavaReflectMethod(targetClass)) {\n\t\t\treturn (T) cloneJavaReflectMethod(source);\n\t\t} else if (targetClass.isPrimitive() || isSunClass(targetClass) || isJavaReflectClass(targetClass)) {\n\t\t\treturn (T) source;\n\t\t} else if (isSerializableCandidate(targetClass, source)) {\n\t\t\treturn (T) serializationClone(source);\n\t\t} else if (targetClass.isEnum()) {\n\t\t\treturn (T) cloneEnum(targetCL, source);\n\t\t} else if (isClass(source)) {\n\t\t\treturn (T) ClassLoaderUtil.loadClass(getType(source), targetCL);\n\t\t} else {\n\t\t\ttarget = isClass(source) ? source : Whitebox.newInstance(targetClass);\n\t\t}\n\n\t\tif (target != null) {\n\t\t\treferenceMap.put(source, target);\n\t\t\tcloneFields(targetCL, targetClass, source, target, referenceMap, shouldCloneStandardJavaTypes);\n\t\t}\n\t\treturn (T) target;\n\t}\n\n\tprivate Object cloneJavaReflectMethod(Object source) {\n\t\tMethod sourceMethod = (Method) source;\n\t\tClass<?> declaringClass = sourceMethod.getDeclaringClass();\n\t\tClass<?> targetClassLoadedWithTargetCL = ClassLoaderUtil.loadClass(declaringClass, targetCL);\n\t\tMethod targetMethod = null;\n\t\ttry {\n\t\t\ttargetMethod = targetClassLoadedWithTargetCL.getDeclaredMethod(sourceMethod.getName(),\n\t\t\t\t\tsourceMethod.getParameterTypes());\n\t\t} catch (Exception e) {\n\t\t\tSafeExceptionRethrower.safeRethrow(e);\n\t\t}\n\t\tif (sourceMethod.isAccessible()) {\n\t\t\ttargetMethod.setAccessible(true);\n\t\t}\n\t\treturn targetMethod;\n\t}\n\n\tprivate boolean isJavaReflectMethod(Class<?> cls) {\n\t\treturn cls.getName().equals(Method.class.getName());\n\t}\n\n\tprivate boolean isSunClass(Class<?> cls) {\n\t\treturn cls.getName().startsWith(\"sun.\");\n\t}\n\n\tprivate boolean isJavaReflectClass(Class<?> cls) {\n\t\treturn cls.getName().startsWith(\"java.lang.reflect\");\n\t}\n\n\tprivate <T> boolean isSerializableCandidate(Class<T> targetClass, Object source) {\n\t\treturn isStandardJavaType(targetClass)\n\t\t\t\t&& (isSerializable(targetClass) || isImpliticlySerializable(targetClass))\n\t\t\t\t&& !Map.class.isAssignableFrom(source.getClass())\n\t\t\t\t&& !Iterable.class.isAssignableFrom(source.getClass());\n\t}\n\n\tprivate static boolean isImpliticlySerializable(Class<?> cls) {\n\t\treturn cls.isPrimitive();\n\t}\n\n\tprivate static boolean isSerializable(Class<?> cls) {\n\t\treturn Serializable.class.isAssignableFrom(cls);\n\t}\n\n\t/*\n\t * Perform simple serialization\n\t */\n\tprivate Object serializationClone(Object source) {\n\t\tObjectOutputStream oos = null;\n\t\tObjectInputStream ois = null;\n\t\ttry {\n\t\t\tByteArrayOutputStream bos = new ByteArrayOutputStream();\n\t\t\toos = new ObjectOutputStream(bos);\n\t\t\toos.writeObject(source);\n\t\t\toos.flush();\n\t\t\tByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());\n\t\t\tois = new ObjectInputStream(bin);\n\t\t\treturn ois.readObject();\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} finally {\n\t\t\tclose(oos);\n\t\t\tclose(ois);\n\t\t}\n\t}\n\n\tprivate void close(Closeable closeable) {\n\t\ttry {\n\t\t\tif (closeable != null) {\n\t\t\t\tcloseable.close();\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t}\n\t}\n\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\tprivate Object cloneEnum(ClassLoader targetCL, Object source) {\n\t\tObject target;\n\t\tfinal Class enumClassLoadedByTargetCL = ClassLoaderUtil.loadClass(getType(source), targetCL);\n\t\ttarget = getEnumValue(source, enumClassLoadedByTargetCL);\n\t\treturn target;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate <T> void cloneFields(ClassLoader targetCL, Class<T> targetClass, Object source, Object target,\n\t\t\tMap<Object, Object> referenceMap, boolean cloneStandardJavaTypes) {\n\t\tClass<?> currentTargetClass = targetClass;\n\t\twhile (currentTargetClass != null) {\n\t\t\tfor (Field field : currentTargetClass.getDeclaredFields()) {\n\t\t\t\tif (field.getAnnotation(doNotClone) != null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfield.setAccessible(true);\n\t\t\t\ttry {\n\t\t\t\t\tfinal Field declaredField = Whitebox.getField(getType(source), field.getName());\n\t\t\t\t\tdeclaredField.setAccessible(true);\n\t\t\t\t\tfinal Object object = declaredField.get(source);\n\t\t\t\t\tfinal Object instantiatedValue;\n\t\t\t\t\tif (object == source) {\n\t\t\t\t\t\tinstantiatedValue = target;\n\t\t\t\t\t} else if (referenceMap.containsKey(object)) {\n\t\t\t\t\t\tinstantiatedValue = referenceMap.get(object);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (object == null && !isIterable(object)) {\n\t\t\t\t\t\t\tinstantiatedValue = object;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tClass<Object> type = getType(object);\n\t\t\t\t\t\t\tif (type.getName().equals(\"void\")) {\n\t\t\t\t\t\t\t\ttype = Class.class.cast(Class.class);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfinal Class<Object> typeLoadedByCL = ClassLoaderUtil.loadClass(type, targetCL\n                            );\n\t\t\t\t\t\t\tif (type.isEnum()) {\n\t\t\t\t\t\t\t\tinstantiatedValue = getEnumValue(object, typeLoadedByCL);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tinstantiatedValue = performClone(typeLoadedByCL, object, cloneStandardJavaTypes);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfinal boolean needsUnsafeWrite = field.isEnumConstant() || isStaticFinalModifier(field);\n\t\t\t\t\tif (needsUnsafeWrite) {\n\t\t\t\t\t\tUnsafeFieldWriter.write(field, target, instantiatedValue);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfield.set(target, instantiatedValue);\n\t\t\t\t\t}\n\t\t\t\t} catch (RuntimeException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentTargetClass = currentTargetClass.getSuperclass();\n\t\t}\n\t}\n\n\tprivate static <T> boolean isStandardJavaType(Class<T> targetClass) {\n\t\treturn targetClass.getName().startsWith(\"java.\");\n\t}\n\n\tprivate static boolean isStaticFinalModifier(final Field field) {\n\t\tfinal int modifiers = field.getModifiers();\n\t\treturn Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)\n\t\t\t\t|| field.getDeclaringClass().equals(Character.class) && field.getName().equals(\"MIN_RADIX\");\n\t}\n\n\tprivate static boolean isIterable(final Object object) {\n\t\treturn object != null && isIterable(object.getClass());\n\t}\n\n\tprivate static boolean isIterable(final Class<?> cls) {\n\t\treturn Iterable.class.isAssignableFrom(cls);\n\t}\n\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\tprivate static Enum getEnumValue(final Object enumValueOfSourceClassloader,\n\t\t\tfinal Class<Object> enumTypeLoadedByTargetCL) {\n\t\treturn Enum.valueOf((Class) enumTypeLoadedByTargetCL, enumValueOfSourceClassloader.toString());\n\t}\n\n\tprivate Object instantiateArray(ClassLoader targetCL, Class<?> arrayClass, Object objectToClone,\n                                    boolean cloneStandardJavaTypes) {\n\t\tfinal int arrayLength = Array.getLength(objectToClone);\n\t\tfinal Object array = Array.newInstance(arrayClass.getComponentType(), arrayLength);\n\t\tfor (int i = 0; i < arrayLength; i++) {\n\t\t\tfinal Object object = Array.get(objectToClone, i);\n\t\t\tfinal Object performClone;\n\t\t\tif (object == null) {\n\t\t\t\tperformClone = null;\n\t\t\t} else {\n\t\t\t\tperformClone = performClone(ClassLoaderUtil.loadClass(getType(object), targetCL),\n\t\t\t\t\t\tobject, cloneStandardJavaTypes);\n\t\t\t}\n\t\t\tArray.set(array, i, performClone);\n\t\t}\n\t\treturn array;\n\t}\n\n\t/**\n\t * Most of this code has been copied from the Sun14ReflectionProvider in the\n\t * XStream project. Some changes has been made, namely if the field is\n\t * static final then the {@link Unsafe#staticFieldOffset(Field)} method is\n\t * used instead of {@link Unsafe#objectFieldOffset(Field)}.\n\t * \n\t * @author Joe Walnes\n\t * @author Brian Slesinsky\n\t * @author Johan Haleby\n\t */\n\tprivate static class UnsafeFieldWriter {\n\t\tprivate final static Unsafe unsafe;\n\t\tprivate final static Exception exception;\n\t\tstatic {\n\t\t\tUnsafe u = null;\n\t\t\tException ex = null;\n\t\t\ttry {\n\t\t\t\tClass<?> objectStreamClass = Class.forName(\"sun.misc.Unsafe\");\n\t\t\t\tField unsafeField = objectStreamClass.getDeclaredField(\"theUnsafe\");\n\t\t\t\tunsafeField.setAccessible(true);\n\t\t\t\tu = (Unsafe) unsafeField.get(null);\n\t\t\t} catch (Exception e) {\n\t\t\t\tex = e;\n\t\t\t}\n\t\t\texception = ex;\n\t\t\tunsafe = u;\n\t\t}\n\n\t\tpublic static void write(Field field, Object object, Object value) {\n\t\t\tif (exception != null) {\n\t\t\t\tthrow new RuntimeException(\"Could not set field \" + object.getClass() + \".\" + field.getName(),\n\t\t\t\t\t\texception);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tfinal long offset;\n\t\t\t\tif (DeepCloner.isStaticFinalModifier(field)) {\n\t\t\t\t\toffset = unsafe.staticFieldOffset(field);\n\t\t\t\t} else {\n\t\t\t\t\toffset = unsafe.objectFieldOffset(field);\n\t\t\t\t}\n\t\t\t\tClass<?> type = field.getType();\n\t\t\t\tif (type.isPrimitive()) {\n\t\t\t\t\tif (type.equals(Integer.TYPE)) {\n\t\t\t\t\t\tunsafe.putInt(object, offset, ((Integer) value).intValue());\n\t\t\t\t\t} else if (type.equals(Long.TYPE)) {\n\t\t\t\t\t\tunsafe.putLong(object, offset, ((Long) value).longValue());\n\t\t\t\t\t} else if (type.equals(Short.TYPE)) {\n\t\t\t\t\t\tunsafe.putShort(object, offset, ((Short) value).shortValue());\n\t\t\t\t\t} else if (type.equals(Character.TYPE)) {\n\t\t\t\t\t\tunsafe.putChar(object, offset, ((Character) value).charValue());\n\t\t\t\t\t} else if (type.equals(Byte.TYPE)) {\n\t\t\t\t\t\tunsafe.putByte(object, offset, ((Byte) value).byteValue());\n\t\t\t\t\t} else if (type.equals(Float.TYPE)) {\n\t\t\t\t\t\tunsafe.putFloat(object, offset, ((Float) value).floatValue());\n\t\t\t\t\t} else if (type.equals(Double.TYPE)) {\n\t\t\t\t\t\tunsafe.putDouble(object, offset, ((Double) value).doubleValue());\n\t\t\t\t\t} else if (type.equals(Boolean.TYPE)) {\n\t\t\t\t\t\tunsafe.putBoolean(object, offset, ((Boolean) value).booleanValue());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new RuntimeException(\"Could not set field \" + object.getClass() + \".\" + field.getName()\n\t\t\t\t\t\t\t\t+ \": Unknown type \" + type);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tunsafe.putObject(object, offset, value);\n\t\t\t\t}\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\tthrow new RuntimeException(\"Could not set field \" + object.getClass() + \".\" + field.getName(), e);\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisClassloaderExecutorTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage powermock.classloading;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.powermock.classloading.SingleClassloaderExecutor;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport powermock.classloading.classes.MyArgument;\nimport powermock.classloading.classes.MyClass;\nimport powermock.classloading.classes.MyEnum;\nimport powermock.classloading.classes.MyEnumHolder;\nimport powermock.classloading.classes.MyHierarchicalFieldHolder;\nimport powermock.classloading.classes.MyIntegerHolder;\nimport powermock.classloading.classes.MyPrimitiveArrayHolder;\nimport powermock.classloading.classes.MyReferenceFieldHolder;\nimport powermock.classloading.classes.MyReturnValue;\nimport powermock.classloading.classes.ReflectionMethodInvoker;\n\nimport java.lang.reflect.Method;\nimport java.util.concurrent.Callable;\n\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertSame;\n\n@Ignore(\"Test are failed on JDK more that 1.6. On Travis we can run only on JDK8 and JDK9\")\npublic class ObjenesisClassloaderExecutorTest {\n    \n    @Test\n    public void loadsObjectGraphInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception {\n        MockClassLoader classloader = createClassloader();\n        final MyReturnValue expectedConstructorValue = new MyReturnValue(new MyArgument(\"first value\"));\n        final MyClass myClass = new MyClass(expectedConstructorValue);\n        final MyArgument expected = new MyArgument(\"A value\");\n        MyReturnValue[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable<MyReturnValue[]>() {\n            public MyReturnValue[] call() throws Exception {\n                assertEquals(JavassistMockClassLoader.class.getName(), this.getClass()\n                                                                           .getClassLoader()\n                                                                           .getClass()\n                                                                           .getName());\n                return myClass.myMethod(expected);\n            }\n        });\n        \n        assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n        \n        final MyReturnValue myReturnValue = actual[0];\n        assertEquals(expectedConstructorValue.getMyArgument().getValue(), myReturnValue.getMyArgument().getValue());\n        assertEquals(expected.getValue(), actual[1].getMyArgument().getValue());\n    }\n    \n    @Test\n    public void loadsObjectGraphThatIncludesPrimitiveValuesInSpecifiedClassloaderAndReturnsResultInOriginalClassloader()\n        throws Exception {\n        MockClassLoader classloader = createClassloader();\n        final Integer expected = 42;\n        final MyIntegerHolder myClass = new MyIntegerHolder(expected);\n        Integer actual = new SingleClassloaderExecutor(classloader).execute(new Callable<Integer>() {\n            public Integer call() throws Exception {\n                assertEquals(JavassistMockClassLoader.class.getName(), this.getClass()\n                                                                           .getClassLoader()\n                                                                           .getClass()\n                                                                           .getName());\n                final int myInteger = myClass.getMyInteger();\n                assertEquals((int) expected, myInteger);\n                return myInteger;\n            }\n        });\n        \n        assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n        \n        assertEquals(expected, actual);\n    }\n    \n    @Test\n    public void loadsObjectGraphThatIncludesEnumsInSpecifiedClassloaderAndReturnsResultInOriginalClassloader()\n        throws Exception {\n        MockClassLoader classloader = createClassloader();\n        final MyEnum expected = MyEnum.MyEnum1;\n        final MyEnumHolder myClass = new MyEnumHolder(expected);\n        MyEnum actual = new SingleClassloaderExecutor(classloader).execute(new Callable<MyEnum>() {\n            public MyEnum call() throws Exception {\n                assertEquals(JavassistMockClassLoader.class.getName(), this.getClass()\n                                                                           .getClassLoader()\n                                                                           .getClass()\n                                                                           .getName());\n                MyEnum myEnum = myClass.getMyEnum();\n                assertEquals(expected, myEnum);\n                return myEnum;\n            }\n        });\n        \n        assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n        assertEquals(expected, actual);\n    }\n    \n    \n    @Test\n    public void loadsObjectGraphThatIncludesPrimitiveArraysInSpecifiedClassloaderAndReturnsResultInOriginalClassloader()\n        throws Exception {\n        MockClassLoader classloader = createClassloader();\n        final int[] expected = new int[]{1, 2};\n        final MyPrimitiveArrayHolder myClass = new MyPrimitiveArrayHolder(expected);\n        int[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable<int[]>() {\n            public int[] call() throws Exception {\n                assertEquals(JavassistMockClassLoader.class.getName(), this.getClass()\n                                                                           .getClassLoader()\n                                                                           .getClass()\n                                                                           .getName());\n                int[] myArray = myClass.getMyArray();\n                assertArrayEquals(expected, myArray);\n                return myArray;\n            }\n        });\n        \n        assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n        assertArrayEquals(expected, actual);\n    }\n    \n    @Test\n    public void usesReferenceCloningWhenTwoFieldsPointToSameInstance() throws Exception {\n        final MockClassLoader classloader = createClassloader();\n        final MyReferenceFieldHolder tested = new MyReferenceFieldHolder();\n        assertSame(tested.getMyArgument1(), tested.getMyArgument2());\n        assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);\n        new SingleClassloaderExecutor(classloader).execute(new Runnable() {\n            public void run() {\n                assertEquals(JavassistMockClassLoader.class.getName(), this.getClass()\n                                                                           .getClassLoader()\n                                                                           .getClass()\n                                                                           .getName());\n                assertEquals(tested.getMyArgument1(), tested.getMyArgument2());\n                assertEquals(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);\n                assertSame(tested.getMyArgument1(), tested.getMyArgument2());\n                // FIXME: This assertion should work:\n                // assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);\n            }\n        });\n    }\n    \n    @Test\n    public void worksWithObjectHierarchy() throws Exception {\n        final MockClassLoader classloader = createClassloader();\n        final MyHierarchicalFieldHolder tested = new MyHierarchicalFieldHolder();\n        assertSame(tested.getMyArgument1(), tested.getMyArgument2());\n        assertEquals(tested.getMyArgument3(), tested.getMyArgument2());\n        new SingleClassloaderExecutor(classloader).execute(new Runnable() {\n            public void run() {\n                assertEquals(JavassistMockClassLoader.class.getName(), this.getClass()\n                                                                           .getClassLoader()\n                                                                           .getClass()\n                                                                           .getName());\n                assertSame(tested.getMyArgument1(), tested.getMyArgument2());\n                assertEquals(tested.getMyArgument3(), tested.getMyArgument2());\n            }\n        });\n    }\n    \n    @Test\n    public void worksWithReflection() throws Exception {\n        final MockClassLoader classloader = createClassloader();\n        final MyArgument myArgument = new MyArgument(\"test\");\n        final MyReturnValue instance = new MyReturnValue(myArgument);\n        Method method = instance.getClass().getMethod(\"getMyArgument\");\n        final ReflectionMethodInvoker tested = new ReflectionMethodInvoker(method, instance);\n        new SingleClassloaderExecutor(classloader).execute(new Runnable() {\n            public void run() {\n                Object invoke = tested.invoke();\n                assertSame(invoke, myArgument);\n            }\n        });\n    }\n    \n    private MockClassLoader createClassloader() {\n        MockClassLoader classloader = new JavassistMockClassLoader(new String[]{MyClass.class.getName(),\n            MyArgument.class.getName(), MyReturnValue.class.getName()});\n        MockTransformer mainMockTransformer = new MockTransformer<Object>() {\n            @Override\n            public ClassWrapper<Object> transform(ClassWrapper<Object> clazz) throws Exception {\n                return clazz;\n            }\n        };\n        classloader.setMockTransformerChain(DefaultMockTransformerChain.newBuilder()\n                                                                       .append(mainMockTransformer)\n                                                                       .build());\n        return classloader;\n    }\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisDeepClonerTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage powermock.classloading;\n\nimport org.junit.Before;\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.powermock.classloading.DeepCloner;\n\nimport java.net.URL;\nimport java.util.Collections;\nimport java.util.List;\n\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotSame;\nimport static org.junit.Assume.assumeTrue;\n\n@Ignore(\"Test are failed on JDK more that 1.6. On Travis we can run only on JDK8 and JDK9\")\npublic class ObjenesisDeepClonerTest {\n    \n    /**\n     * These tests crashes the JVM on version 1.8\n     */\n    @Before\n    public void onlyRunTestsOnNonJava8Environment() throws Exception {\n        final String property = System.getProperty(\"java.specification.version\");\n        final float maximumVersion = 1.6f;\n        assumeTrue(\"Current JDK version  \" + property + \" expected is more than than \" + maximumVersion, Float.valueOf(property) <= maximumVersion);\n    }\n    \n    @Test\n    public void clonesJavaInstances() throws Exception {\n        final URL original = new URL(\"http://www.powermock.org\");\n        URL clone = new DeepCloner().clone(original);\n        assertEquals(clone, original);\n        assertNotSame(clone, original);\n    }\n    \n    @Test\n    public void clonesUnmodifiableLists() throws Exception {\n        final UnmodifiableListExample original = new UnmodifiableListExample();\n        UnmodifiableListExample clone = new DeepCloner().clone(original);\n        assertEquals(clone, original);\n        assertNotSame(clone, original);\n    }\n    \n    @Test\n    public void clonesArraysWithNullValues() throws Exception {\n        Object[] original = new Object[]{\"Test\", null};\n        Object[] clone = new DeepCloner().clone(original);\n        assertArrayEquals(clone, original);\n        assertNotSame(clone, original);\n    }\n    \n}\n\nclass UnmodifiableListExample {\n    private List<NotSerializable> cl = Collections.singletonList(new NotSerializable());\n    \n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + ((cl == null) ? 0 : cl.hashCode());\n        return result;\n    }\n    \n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) { return true; }\n        if (obj == null) { return false; }\n        if (getClass() != obj.getClass()) { return false; }\n        powermock.classloading.UnmodifiableListExample other = (powermock.classloading.UnmodifiableListExample) obj;\n        if (cl == null) {\n            if (other.cl != null) { return false; }\n        } else if (!cl.equals(other.cl)) { return false; }\n        return true;\n    }\n}\n\nclass NotSerializable {\n    private final String state = \"Nothing\";\n    \n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + ((state == null) ? 0 : state.hashCode());\n        return result;\n    }\n    \n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) { return true; }\n        if (obj == null) { return false; }\n        if (getClass() != obj.getClass()) { return false; }\n        powermock.classloading.NotSerializable other = (powermock.classloading.NotSerializable) obj;\n        if (state == null) {\n            if (other.state != null) { return false; }\n        } else if (!state.equals(other.state)) { return false; }\n        return true;\n    }\n}"
  },
  {
    "path": "powermock-classloading/powermock-classloading-xstream/src/main/java/org/powermock/classloading/DeepCloner.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.classloading;\n\nimport com.thoughtworks.xstream.XStream;\nimport org.powermock.classloading.spi.DeepClonerSPI;\n\n/**\n * <p>\n * The purpose of the deep cloner is to create a deep clone of an object. An\n * object can also be cloned to a different class-loader.\n * </p>\n */\npublic class DeepCloner implements DeepClonerSPI {\n    private final XStream xStream;\n\n\t/**\n\t * Clone using the supplied ClassLoader.\n\t * @param classLoader - the classloader to loaded cloned classes.\n\t */\n\tpublic DeepCloner(ClassLoader classLoader) {\n        xStream = new XStream();\n\t\tdisableSecurity();\n\t\txStream.omitField(SingleClassloaderExecutor.class, \"classloader\");\n        xStream.setClassLoader(classLoader);\n\t}\n\n\tprivate void disableSecurity() {\n\t\tXStream.setupDefaultSecurity(xStream);\n\t\txStream.allowTypesByRegExp(new String[]{\".*\"});\n\t}\n\n\t/**\n\t * Clone using the current ContextClassLoader.\n\t */\n\tpublic DeepCloner() {\n\t\tthis(Thread.currentThread().getContextClassLoader());\n\t}\n\n\n\n\t/**\n\t * Clones an object.\n\t *\n     * @param objectToClone the object to clone.\n\t * @return A deep clone of the object to clone.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T clone(T objectToClone) {\n        final String serialized = xStream.toXML(objectToClone);\n        return (T) xStream.fromXML(serialized);\n    }\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamClassloaderExecutorTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage powermock.classloading;\n\nimport org.junit.Test;\nimport org.powermock.classloading.SingleClassloaderExecutor;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport powermock.classloading.classes.MyArgument;\nimport powermock.classloading.classes.MyClass;\nimport powermock.classloading.classes.MyCollectionHolder;\nimport powermock.classloading.classes.MyEnum;\nimport powermock.classloading.classes.MyEnumHolder;\nimport powermock.classloading.classes.MyHierarchicalFieldHolder;\nimport powermock.classloading.classes.MyHierarchicalOverloadedFieldHolder;\nimport powermock.classloading.classes.MyIntegerHolder;\nimport powermock.classloading.classes.MyPrimitiveArrayHolder;\nimport powermock.classloading.classes.MyReferenceFieldHolder;\nimport powermock.classloading.classes.MyReturnValue;\nimport powermock.classloading.classes.MyStaticFinalArgumentHolder;\nimport powermock.classloading.classes.MyStaticFinalNumberHolder;\nimport powermock.classloading.classes.MyStaticFinalPrimitiveHolder;\nimport powermock.classloading.classes.ReflectionMethodInvoker;\n\nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.LinkedList;\nimport java.util.concurrent.Callable;\n\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotSame;\nimport static org.junit.Assert.assertSame;\nimport static org.junit.Assert.assertTrue;\n\npublic class XStreamClassloaderExecutorTest {\n\n\t@Test\n\tpublic void loadsObjectGraphInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception {\n\t\tMockClassLoader classloader = createClassloader();\n\t\tfinal MyReturnValue expectedConstructorValue = new MyReturnValue(new MyArgument(\"first value\"));\n\t\tfinal MyClass myClass = new MyClass(expectedConstructorValue);\n\t\tfinal MyArgument expected = new MyArgument(\"A value\");\n\t\tMyReturnValue[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable<MyReturnValue[]>() {\n\t\t\tpublic MyReturnValue[] call() throws Exception {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\treturn myClass.myMethod(expected);\n\t\t\t}\n\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\n\t\tfinal MyReturnValue myReturnValue = actual[0];\n\t\tassertEquals(expectedConstructorValue.getMyArgument().getValue(), myReturnValue.getMyArgument().getValue());\n\t\tassertEquals(expected.getValue(), actual[1].getMyArgument().getValue());\n\t}\n\n\t@Test\n\tpublic void loadsObjectGraphThatIncludesPrimitiveValuesInSpecifiedClassloaderAndReturnsResultInOriginalClassloader()\n\t\t\tthrows Exception {\n\t\tMockClassLoader classloader = createClassloader();\n\t\tfinal Integer expected = 42;\n\t\tfinal MyIntegerHolder myClass = new MyIntegerHolder(expected);\n\t\tInteger actual = new SingleClassloaderExecutor(classloader).execute(new Callable<Integer>() {\n\t\t\tpublic Integer call() throws Exception {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\tfinal int myInteger = myClass.getMyInteger();\n\t\t\t\tassertEquals((int) expected, myInteger);\n\t\t\t\treturn myInteger;\n\t\t\t}\n\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void loadsObjectGraphThatIncludesEnumsInSpecifiedClassloaderAndReturnsResultInOriginalClassloader()\n\t\t\tthrows Exception {\n\t\tMockClassLoader classloader = createClassloader();\n\t\tfinal MyEnum expected = MyEnum.MyEnum1;\n\t\tfinal MyEnumHolder myClass = new MyEnumHolder(expected);\n\t\tMyEnum actual = new SingleClassloaderExecutor(classloader).execute(new Callable<MyEnum>() {\n\t\t\tpublic MyEnum call() throws Exception {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\tMyEnum myEnum = myClass.getMyEnum();\n\t\t\t\tassertEquals(expected, myEnum);\n\t\t\t\treturn myEnum;\n\t\t\t}\n\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void clonesStaticFinalObjectFields() throws Exception {\n\t\tMockClassLoader classloader = createClassloader();\n\t\tfinal MyStaticFinalArgumentHolder expected = new MyStaticFinalArgumentHolder();\n\t\tMyStaticFinalArgumentHolder actual = new SingleClassloaderExecutor(classloader)\n\t\t\t\t.execute(new Callable<MyStaticFinalArgumentHolder>() {\n\t\t\t\t\tpublic MyStaticFinalArgumentHolder call() throws Exception {\n\t\t\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass()\n\t\t\t\t\t\t\t\t.getName());\n\t\t\t\t\t\tMyStaticFinalArgumentHolder actual = new MyStaticFinalArgumentHolder();\n\t\t\t\t\t\tassertEquals(expected.getMyObject(), actual.getMyObject());\n\t\t\t\t\t\treturn actual;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\t\tassertEquals(expected.getMyObject(), actual.getMyObject());\n\t}\n\n\t@Test\n\tpublic void clonesStaticFinalPrimitiveFields() throws Exception {\n\t\tMockClassLoader classloader = createClassloader();\n\t\tfinal MyStaticFinalPrimitiveHolder expected = new MyStaticFinalPrimitiveHolder();\n\t\tMyStaticFinalPrimitiveHolder actual = new SingleClassloaderExecutor(classloader)\n\t\t\t\t.execute(new Callable<MyStaticFinalPrimitiveHolder>() {\n\t\t\t\t\tpublic MyStaticFinalPrimitiveHolder call() throws Exception {\n\t\t\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass()\n\t\t\t\t\t\t\t\t.getName());\n\t\t\t\t\t\tMyStaticFinalPrimitiveHolder actual = new MyStaticFinalPrimitiveHolder();\n\t\t\t\t\t\tassertEquals(expected.getMyInt(), actual.getMyInt());\n\t\t\t\t\t\treturn actual;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\t\tassertEquals(expected.getMyInt(), actual.getMyInt());\n\t}\n\n\t@Test\n\tpublic void clonesStaticFinalNumberFields() throws Exception {\n\t\tMockClassLoader classloader = createClassloader();\n\t\tfinal MyStaticFinalNumberHolder expected = new MyStaticFinalNumberHolder();\n\t\tMyStaticFinalNumberHolder actual = new SingleClassloaderExecutor(classloader)\n\t\t\t\t.execute(new Callable<MyStaticFinalNumberHolder>() {\n\t\t\t\t\tpublic MyStaticFinalNumberHolder call() throws Exception {\n\t\t\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass()\n\t\t\t\t\t\t\t\t.getName());\n\t\t\t\t\t\tMyStaticFinalNumberHolder actual = new MyStaticFinalNumberHolder();\n\t\t\t\t\t\tassertEquals(expected.getMyLong(), actual.getMyLong());\n\t\t\t\t\t\treturn actual;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\t\tassertEquals(expected.getMyLong(), actual.getMyLong());\n\t}\n\n\t@Test\n\tpublic void loadsObjectGraphThatIncludesPrimitiveArraysInSpecifiedClassloaderAndReturnsResultInOriginalClassloader()\n\t\t\tthrows Exception {\n\t\tMockClassLoader classloader = createClassloader();\n\t\tfinal int[] expected = new int[] { 1, 2 };\n\t\tfinal MyPrimitiveArrayHolder myClass = new MyPrimitiveArrayHolder(expected);\n\t\tint[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable<int[]>() {\n\t\t\tpublic int[] call() throws Exception {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\tint[] myArray = myClass.getMyArray();\n\t\t\t\tassertArrayEquals(expected, myArray);\n\t\t\t\treturn myArray;\n\t\t\t}\n\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\t\tassertArrayEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void loadsObjectGraphThatIncludesCollectionInSpecifiedClassloaderAndReturnsResultInOriginalClassloader()\n\t\t\tthrows Exception {\n\t\tfinal MockClassLoader classloader = createClassloader();\n\t\tfinal Collection<MyReturnValue> expected = new LinkedList<MyReturnValue>();\n\t\texpected.add(new MyReturnValue(new MyArgument(\"one\")));\n\t\texpected.add(new MyReturnValue(new MyArgument(\"two\")));\n\t\tfinal MyCollectionHolder myClass = new MyCollectionHolder(expected);\n\t\tCollection<?> actual = new SingleClassloaderExecutor(classloader).execute(new Callable<Collection<?>>() {\n\t\t\tpublic Collection<?> call() throws Exception {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\tCollection<?> myCollection = myClass.getMyCollection();\n\t\t\t\tfor (Object object : myCollection) {\n\t\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), object.getClass().getClassLoader().getClass()\n\t\t\t\t\t\t\t.getName());\n\t\t\t\t}\n\t\t\t\treturn myCollection;\n\t\t\t}\n\t\t});\n\n\t\tassertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName()));\n\t\tassertEquals(2, actual.size());\n\t\tfor (Object object : actual) {\n\t\t\tfinal String value = ((MyReturnValue) object).getMyArgument().getValue();\n\t\t\tassertTrue(value.equals(\"one\") || value.equals(\"two\"));\n\t\t}\n\t}\n\n\t@Test\n\tpublic void usesReferenceCloningWhenTwoFieldsPointToSameInstance() throws Exception {\n\t\tfinal MockClassLoader classloader = createClassloader();\n\t\tfinal MyReferenceFieldHolder tested = new MyReferenceFieldHolder();\n\t\tassertSame(tested.getMyArgument1(), tested.getMyArgument2());\n\t\tassertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);\n\t\tnew SingleClassloaderExecutor(classloader).execute(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\tassertEquals(tested.getMyArgument1(), tested.getMyArgument2());\n\t\t\t\tassertEquals(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);\n\t\t\t\tassertSame(tested.getMyArgument1(), tested.getMyArgument2());\n\t\t\t\t// FIXME: This assertion should work:\n\t\t\t\t// assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);\n\t\t\t}\n\t\t});\n\t}\n\n\t@Test\n\tpublic void worksWithObjectHierarchy() throws Exception {\n\t\tfinal MockClassLoader classloader = createClassloader();\n\t\tfinal MyHierarchicalFieldHolder tested = new MyHierarchicalFieldHolder();\n\t\tassertSame(tested.getMyArgument1(), tested.getMyArgument2());\n\t\tassertEquals(tested.getMyArgument3(), tested.getMyArgument2());\n\t\tnew SingleClassloaderExecutor(classloader).execute(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\tassertSame(tested.getMyArgument1(), tested.getMyArgument2());\n\t\t\t\tassertEquals(tested.getMyArgument3(), tested.getMyArgument2());\n\t\t\t}\n\t\t});\n\t}\n\n\t@Test\n\tpublic void worksWithObjectHierarchyAndOverloadedFields() throws Exception {\n\t\tfinal MockClassLoader classloader = createClassloader();\n\t\tfinal MyHierarchicalOverloadedFieldHolder tested = new MyHierarchicalOverloadedFieldHolder();\n\t\tassertSame(tested.getMyArgument1(), tested.getMyArgument2());\n\t\tassertEquals(tested.getMyArgument1(), tested.getMyArgument3());\n\t\tassertSame(tested.getMyArgument3(), MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT);\n\t\tassertNotSame(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT);\n\t\tassertEquals(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT);\n\t\tnew SingleClassloaderExecutor(classloader).execute(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tassertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());\n\t\t\t\tassertSame(tested.getMyArgument1(), tested.getMyArgument2());\n\t\t\t\tassertEquals(tested.getMyArgument1(), tested.getMyArgument3());\n                // Note: Cannot be same using X-Stream\n\t\t\t\tassertEquals(tested.getMyArgument3(), MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT);\n\t\t\t\tassertNotSame(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT);\n\t\t\t\tassertEquals(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT);\n\t\t\t}\n\t\t});\n\t}\n\n\t@Test\n\tpublic void worksWithReflection() throws Exception {\n\t\tfinal MockClassLoader classloader = createClassloader();\n\t\tfinal MyArgument myArgument = new MyArgument(\"test\");\n\t\tfinal MyReturnValue instance = new MyReturnValue(myArgument);\n\t\tMethod method = instance.getClass().getMethod(\"getMyArgument\");\n\t\tfinal ReflectionMethodInvoker tested = new ReflectionMethodInvoker(method, instance);\n\t\tnew SingleClassloaderExecutor(classloader).execute(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tObject invoke = tested.invoke();\n\t\t\t\tassertSame(invoke, myArgument);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate MockClassLoader createClassloader() {\n\t\tMockClassLoader classloader = new JavassistMockClassLoader(new String[] { MyClass.class.getName(),\n\t\t\t\tMyArgument.class.getName(), MyReturnValue.class.getName() });\n\t\tMockTransformer mainMockTransformer = new MockTransformer<Object>() {\n\t\t\t@Override\n\t\t\tpublic ClassWrapper<Object> transform(ClassWrapper<Object> clazz) throws Exception {\n\t\t\t\treturn clazz;\n\t\t\t}\n\t\t};\n\t\tclassloader.setMockTransformerChain(DefaultMockTransformerChain.newBuilder().append(mainMockTransformer).build());\n\t\treturn classloader;\n\t}\n}\n"
  },
  {
    "path": "powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamDeepClonerTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage powermock.classloading;\n\nimport org.junit.Test;\nimport org.powermock.classloading.DeepCloner;\n\nimport java.net.URL;\nimport java.util.Collections;\nimport java.util.List;\n\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotSame;\n\npublic class XStreamDeepClonerTest {\n\n    @Test\n    public void clonesJavaInstances() throws Exception {\n        final URL original = new URL(\"http://www.powermock.org\");\n        URL clone = new DeepCloner().clone(original);\n        assertEquals(clone, original);\n        assertNotSame(clone, original);\n    }\n\n    @Test\n    public void clonesUnmodifiableLists() throws Exception {\n        final UnmodifiableListExample original = new UnmodifiableListExample();\n        UnmodifiableListExample clone = new DeepCloner().clone(original);\n        assertEquals(clone, original);\n        assertNotSame(clone, original);\n    }\n\n    @Test\n    public void clonesArraysWithNullValues() throws Exception {\n        Object[] original = new Object[] { \"Test\", null };\n        Object[] clone = new DeepCloner().clone(original);\n        assertArrayEquals(clone, original);\n        assertNotSame(clone, original);\n    }\n\n}\n\nclass UnmodifiableListExample {\n    private List<NotSerializable> cl = Collections.singletonList(new NotSerializable());\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + ((cl == null) ? 0 : cl.hashCode());\n        return result;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj)\n            return true;\n        if (obj == null)\n            return false;\n        if (getClass() != obj.getClass())\n            return false;\n        powermock.classloading.UnmodifiableListExample other = (powermock.classloading.UnmodifiableListExample) obj;\n        if (cl == null) {\n            if (other.cl != null)\n                return false;\n        } else if (!cl.equals(other.cl))\n            return false;\n        return true;\n    }\n}\n\nclass NotSerializable {\n    private final String state = \"Nothing\";\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + ((state == null) ? 0 : state.hashCode());\n        return result;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj)\n            return true;\n        if (obj == null)\n            return false;\n        if (getClass() != obj.getClass())\n            return false;\n        powermock.classloading.NotSerializable other = (powermock.classloading.NotSerializable) obj;\n        if (state == null) {\n            if (other.state != null)\n                return false;\n        } else if (!state.equals(other.state))\n            return false;\n        return true;\n    }\n}"
  },
  {
    "path": "powermock-core/build.gradle",
    "content": "\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/PowerMockInternalException.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock;\n\npublic class PowerMockInternalException extends RuntimeException{\n    \n    private static final String MESSAGE = \"PowerMock internal error has happened. This exception is thrown in unexpected cases, that normally should never happen. Please, report about the issue to PowerMock issues tacker. \";\n    \n    public PowerMockInternalException(final Throwable cause) {\n        super(MESSAGE, cause);\n    }\n    \n    public PowerMockInternalException(final String message) {\n        super(MESSAGE + message);\n    }\n    \n    public PowerMockInternalException(final String message, final Throwable cause) {\n        super(MESSAGE + message, cause);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/Configuration.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration;\n\n/**\n * The general interface for all types configurations that could be obtained via {@link GlobalConfiguration}.\n * <p>\n * All user defined configurations are read from the properties file:\n * </p><pre>org/powermock/extensions/configuration.properties</pre>\n * <p>\n * By default the file is not exist and default values are used.\n * </p>\n *\n * @param <T> configuration implementer class.\n * @since 1.7.0\n */\npublic interface Configuration<T extends Configuration> {\n    \n    /**\n     * Merge values of the configuration with values of <code>configuration</code>.\n     * Values with the same keys from the <code>configuration</code>\n     * overwrite value in the current configuration.\n     *\n     * @param configuration source configurations.\n     * @return a new instance of {@link Configuration} with merged values.\n     */\n    T merge(T configuration);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/ConfigurationFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration;\n\npublic interface ConfigurationFactory {\n    <T extends Configuration<T>> T create(Class<T> configurationType);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/ConfigurationType.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration;\n\npublic enum ConfigurationType {\n    Mockito(\"mockito\", MockitoConfiguration.class),\n    PowerMock(\"powermock\", PowerMockConfiguration.class);\n    \n    private final String prefix;\n    private final Class<? extends Configuration> configurationClass;\n    \n    ConfigurationType(final String prefix,\n                      final Class<? extends Configuration> configurationClass) {\n        this.prefix = prefix;\n        this.configurationClass = configurationClass;\n    }\n    \n    public String getPrefix() {\n        return prefix;\n    }\n    \n    public static <T extends Configuration> ConfigurationType forClass(final Class<T> configurationClass) {\n        for (ConfigurationType configurationType : ConfigurationType.values()) {\n            if (configurationType.configurationClass.isAssignableFrom(configurationClass)){\n                return configurationType;\n            }\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/GlobalConfiguration.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration;\n\nimport org.powermock.configuration.support.ConfigurationFactoryImpl;\n\n/**\n * <p>\n * The class provides static access to {@link Configuration}.\n * The class uses {@link ThreadLocal} for storing of each type of configuration.\n * In result a one instance of each configuration type is created per thread.\n * </p>\n *\n * @since 1.7.0\n */\npublic final class GlobalConfiguration {\n    \n    private static ConfigurationFactory configurationFactory = new ConfigurationFactoryImpl();\n    \n    private static final ThreadLocal<MockitoConfiguration> MOCKITO_CONFIGURATION = new ThreadLocal<MockitoConfiguration>();\n    private static final ThreadLocal<PowerMockConfiguration> POWER_MOCK_CONFIGURATION = new ThreadLocal<PowerMockConfiguration>();\n    \n    public static MockitoConfiguration mockitoConfiguration() {\n        return new GlobalConfiguration().getMockitoConfiguration();\n    }\n    \n    public static PowerMockConfiguration powerMockConfiguration() {\n        return new GlobalConfiguration().getPowerMockConfiguration();\n    }\n    \n    public static void clear() {\n        configurationFactory = new ConfigurationFactoryImpl();\n        MOCKITO_CONFIGURATION.remove();\n        POWER_MOCK_CONFIGURATION.remove();\n    }\n    \n    public static void setConfigurationFactory(final ConfigurationFactory configurationFactory) {\n        GlobalConfiguration.configurationFactory = configurationFactory;\n    }\n    \n    private GlobalConfiguration() {\n        if (MOCKITO_CONFIGURATION.get() == null) {\n            MOCKITO_CONFIGURATION.set(createConfig(MockitoConfiguration.class));\n        }\n        if (POWER_MOCK_CONFIGURATION.get() == null) {\n            POWER_MOCK_CONFIGURATION.set(createConfig(PowerMockConfiguration.class));\n        }\n    }\n    \n    private PowerMockConfiguration getPowerMockConfiguration() {\n        return POWER_MOCK_CONFIGURATION.get();\n    }\n    \n    private MockitoConfiguration getMockitoConfiguration() {\n        return MOCKITO_CONFIGURATION.get();\n    }\n    \n    private <T extends Configuration<T>> T createConfig(Class<T> configurationClass) {\n        return configurationFactory.create(configurationClass);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/MockitoConfiguration.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration;\n\npublic class MockitoConfiguration implements Configuration<MockitoConfiguration> {\n    \n    private String mockMakerClass;\n    \n    public MockitoConfiguration() {\n        // Used by configuration reader to create an instance\n    }\n    \n    private MockitoConfiguration(final String mockMakerClass) {\n        this.mockMakerClass = mockMakerClass;\n    }\n    \n    public String getMockMakerClass() {\n        return mockMakerClass;\n    }\n    \n    public void setMockMakerClass(final String mockMakerClass) {\n        this.mockMakerClass = mockMakerClass;\n    }\n    \n    @Override\n    public MockitoConfiguration merge(final MockitoConfiguration configuration) {\n        if (configuration != null && configuration.getMockMakerClass() != null) {\n            return new MockitoConfiguration(configuration.getMockMakerClass());\n        } else {\n            return this;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/PowerMockConfiguration.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration;\n\nimport org.powermock.core.classloader.ByteCodeFramework;\nimport org.powermock.utils.ArrayUtil;\n\n/**\n * The class provides list of setting for PowerMock.\n * The properties with `powermock` prefix are mapped to the class.\n *\n * @since 1.7.0\n * @see Configuration\n */\npublic class PowerMockConfiguration implements Configuration<PowerMockConfiguration> {\n    private String[] globalIgnore;\n    private ByteCodeFramework byteCodeFramework;\n    \n    public String[] getGlobalIgnore() {\n        return globalIgnore;\n    }\n    \n    public void setGlobalIgnore(final String[] globalIgnore) {\n        this.globalIgnore = globalIgnore;\n    }\n    \n    public ByteCodeFramework getByteCodeFramework() {\n        return byteCodeFramework;\n    }\n    \n    public void setByteCodeFramework(final ByteCodeFramework byteCodeFramework) {\n        this.byteCodeFramework = byteCodeFramework;\n    }\n    \n    @Override\n    public PowerMockConfiguration merge(final PowerMockConfiguration configuration) {\n        if (configuration == null) {\n            return this;\n        } else {\n            PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration();\n    \n            String[] globalIgnore = ArrayUtil.mergeArrays(this.globalIgnore, configuration.globalIgnore);\n            \n            powerMockConfiguration.setGlobalIgnore(globalIgnore);\n            if (configuration.byteCodeFramework == null) {\n                powerMockConfiguration.setByteCodeFramework(byteCodeFramework);\n            }else {\n                powerMockConfiguration.setByteCodeFramework(configuration.byteCodeFramework);\n            }\n            \n            return powerMockConfiguration;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationBuilder.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration.support;\n\nimport org.powermock.PowerMockInternalException;\nimport org.powermock.configuration.Configuration;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\n\nclass ConfigurationBuilder<T extends Configuration<?>> {\n    \n    static <C extends Configuration<?>> ConfigurationBuilder<C> createConfigurationFor(final Class<C> configurationType) {\n        return new ConfigurationBuilder<C>(configurationType);\n    }\n    \n    private final Map<String, String> alias;\n    private final Class<T> configurationType;\n    \n    private ConfigurationBuilder(final Class<T> configurationType) {\n        this.configurationType = configurationType;\n        alias = new HashMap<String, String>();\n    }\n    \n    ConfigurationBuilder<T> withValueAlias(final String alias, final String value) {\n        this.alias.put(alias, value);\n        return this;\n    }\n    \n    T fromFile(final String configurationLocation) {\n        final Properties properties = new PropertiesLoader().load(configurationLocation);\n        return fromProperties(properties);\n    }\n    \n    T fromProperties(final Properties properties) {\n        final ConfigurationCreator configurationCreator = new ConfigurationCreator(alias);\n        return configurationCreator.create(configurationType, properties);\n    }\n    \n    private static class ConfigurationCreator {\n    \n        private final ValueAliases alias;\n        \n        private ConfigurationCreator(final Map<String, String> alias) {\n            this.alias = new ValueAliases(alias);\n        }\n        \n        public <T extends Configuration> T create(Class<T> configurationClass, final Properties properties) {\n            try {\n                T configuration = configurationClass.newInstance();\n                if (properties != null) {\n                    mapConfiguration(configurationClass, configuration, properties);\n                }\n                return configuration;\n            } catch (Exception e) {\n                throw new PowerMockInternalException(e);\n            }\n        }\n        \n        private <T extends Configuration> void mapConfiguration(final Class<T> configurationClass,\n                                                                final T configuration,\n                                                                final Properties properties) {\n            new ConfigurationMapper<T>(configurationClass, configuration, alias).map(properties);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationFactoryImpl.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration.support;\n\nimport org.powermock.configuration.Configuration;\nimport org.powermock.configuration.ConfigurationFactory;\nimport org.powermock.utils.Asserts;\n\nimport java.util.Properties;\n\nimport static org.powermock.configuration.support.ConfigurationBuilder.createConfigurationFor;\n\npublic class ConfigurationFactoryImpl implements ConfigurationFactory {\n    \n    private static final String USER_CONFIGURATION = \"org/powermock/extensions/configuration.properties\";\n    private static final String DEFAULT_CONFIGURATION = \"org/powermock/default.properties\";\n    \n    private final String userConfigurationLocation;\n    private final String defaultConfigurationLocation;\n    \n    public ConfigurationFactoryImpl() {\n        this(USER_CONFIGURATION, DEFAULT_CONFIGURATION);\n    }\n    \n    ConfigurationFactoryImpl(final String userConfigurationLocation, final String defaultConfigurationLocation) {\n        this.userConfigurationLocation = userConfigurationLocation;\n        this.defaultConfigurationLocation = defaultConfigurationLocation;\n    }\n    \n    ConfigurationFactoryImpl(final String defaultConfigurationLocation) {\n        this(USER_CONFIGURATION, defaultConfigurationLocation);\n    }\n    \n    @Override\n    public <T extends Configuration<T>> T create(final Class<T> configurationType) {\n        T environmentConfiguration = readEnvironmentConfiguration(configurationType);\n        T configuration = readUserConfiguration(configurationType);\n        T defaultConfiguration = readDefault(configurationType);\n        return defaultConfiguration.merge(configuration.merge(environmentConfiguration));\n    }\n    \n    private <T extends Configuration<T>> T readEnvironmentConfiguration(final Class<T> configurationType) {\n        final Properties properties = new Properties();\n        properties.putAll(System.getenv());\n        return createConfigurationFor(configurationType)\n                   .fromProperties(properties);\n        \n    }\n    \n    private <T extends Configuration> T  readDefault(final Class<T> configurationType) {\n    \n        final T configuration = createConfigurationFor(configurationType)\n                                    .fromFile(getDefaultConfigurationLocation());\n    \n        Asserts.internalAssertNotNull(configuration, \"Default configuration is null.\");\n        return configuration;\n    }\n    \n    private <T extends Configuration> T  readUserConfiguration(final Class<T> configurationType) {\n        return createConfigurationFor(configurationType)\n                   .fromFile(getUserConfigurationLocation());\n    }\n    \n    private String getDefaultConfigurationLocation() {\n        return defaultConfigurationLocation;\n    }\n    \n    private String getUserConfigurationLocation() {\n        return userConfigurationLocation;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationMapper.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration.support;\n\nimport org.powermock.configuration.Configuration;\nimport org.powermock.configuration.ConfigurationType;\nimport org.powermock.PowerMockInternalException;\n\nimport java.beans.BeanInfo;\nimport java.beans.Introspector;\nimport java.beans.PropertyDescriptor;\nimport java.util.Properties;\n\nclass ConfigurationMapper<T extends Configuration> {\n    private final Class<T> configurationClass;\n    private final T configuration;\n    private final ValueAliases aliases;\n    \n    ConfigurationMapper(final Class<T> configurationClass, final T configuration, final ValueAliases aliases) {\n        this.configurationClass = configurationClass;\n        this.configuration = configuration;\n        this.aliases = aliases;\n    }\n    \n    public void map(final Properties properties) {\n        try {\n            \n            BeanInfo info = Introspector.getBeanInfo(configurationClass, Object.class);\n            PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();\n            \n            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {\n                if (propertyDescriptor.getWriteMethod() != null) {\n                    mapProperty(propertyDescriptor, properties);\n                }\n            }\n            \n        } catch (Exception e) {\n            throw new PowerMockInternalException(e);\n        }\n    }\n    \n    private void mapProperty(final PropertyDescriptor propertyDescriptor, final Properties properties) {\n        \n        final ConfigurationKey key = new ConfigurationKey(ConfigurationType.forClass(configurationClass), propertyDescriptor.getName());\n        final String value = aliases.findValue((String) properties.get(key.toString()));\n        \n        PropertyWriter.forProperty(propertyDescriptor)\n                      .writeProperty(propertyDescriptor, this.configuration, value);\n    }\n    \n    private static class ConfigurationKey {\n        private final ConfigurationType configurationType;\n        private final String name;\n        \n        private ConfigurationKey(final ConfigurationType configurationType, final String name) {\n            this.configurationType = configurationType;\n            this.name = name;\n        }\n        \n        @Override\n        public String toString() {\n            StringBuilder key = new StringBuilder();\n            \n            if (configurationType.getPrefix() != null) {\n                key.append(configurationType.getPrefix());\n                key.append(\".\");\n            }\n            \n            for (int i = 0; i < name.length(); i++) {\n                char c = name.charAt(i);\n                if (Character.isUpperCase(c)) {\n                    key.append('-');\n                    key.append(Character.toLowerCase(c));\n                } else {\n                    key.append(c);\n                }\n            }\n            return key.toString();\n        }\n    }\n    \n    @SuppressWarnings(\"unchecked\")\n    private enum PropertyWriter {\n        ArrayWriter {\n            @Override\n            public void writeProperty(final PropertyDescriptor pd, final Object target, final String value) {\n                try {\n                    if (value != null) {\n                        String[] array = value.split(\",\");\n                        pd.getWriteMethod().invoke(target, (Object) array);\n                    }\n                } catch (Exception e) {\n                    throw new PowerMockInternalException(e);\n                }\n            }\n        },\n        StringWriter {\n            @Override\n            public void writeProperty(final PropertyDescriptor pd, final Object target, final String value) {\n                try {\n                    if (value != null) {\n                        pd.getWriteMethod().invoke(target, value);\n                    }\n                } catch (Exception e) {\n                    throw new PowerMockInternalException(e);\n                }\n            }\n        },\n        EnumWriter {\n            @Override\n            public void writeProperty(final PropertyDescriptor pd, final Object target, final String value) {\n                try {\n                    if (value != null) {\n                        final Class<Enum<?>> enumClass = (Class<Enum<?>>) pd.getPropertyType();\n                        final Enum<?>[] constants = enumClass.getEnumConstants();\n                        for (Enum<?> constant : constants) {\n                            if(value.equals(constant.name())){\n                                pd.getWriteMethod().invoke(target, constant);\n                                return;\n                            }\n                        }\n                        throw new PowerMockInternalException(String.format(\n                            \"Find unknown enum constant `%s` for type `%s` during reading configuration.\", value, enumClass\n                        ));\n                    }\n                } catch (Exception e) {\n                    throw new PowerMockInternalException(e);\n                }\n            }\n        };\n    \n        private static PropertyWriter forProperty(final PropertyDescriptor pd) {\n            if (String[].class.isAssignableFrom(pd.getPropertyType())) {\n                return ArrayWriter;\n            } else if (Enum.class.isAssignableFrom(pd.getPropertyType())) {\n                return EnumWriter;\n            } else {\n                return StringWriter;\n            }\n        }\n        \n        abstract void writeProperty(final PropertyDescriptor propertyDescriptor, final Object target, final String value);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/support/PropertiesFinder.java",
    "content": "package org.powermock.configuration.support;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.List;\n\n\nclass PropertiesFinder {\n    \n    private final ClassLoader classLoader;\n    \n    PropertiesFinder(final ClassLoader classLoader) {\n        this.classLoader = classLoader;\n    }\n    \n    List<ConfigurationSource> find(final String configurationFile) throws IOException, URISyntaxException {\n        \n        final List<ConfigurationSource> configurations = new ArrayList<ConfigurationSource>();\n        \n        Enumeration<URL> resources = classLoader.getResources(configurationFile);\n        \n        while (resources.hasMoreElements()) {\n            URL candidate = resources.nextElement();\n            configurations.add(new ConfigurationSource(candidate.getFile(), candidate.openStream()));\n        }\n        \n        return configurations;\n    }\n    \n    static class ConfigurationSource {\n        \n        private final String location;\n        private final InputStream inputStream;\n        \n        \n        ConfigurationSource(final String location, final InputStream inputStream) {\n            this.location = location;\n            this.inputStream = inputStream;\n        }\n        \n        InputStream inputStream() {\n            return inputStream;\n        }\n        \n        String getLocation() {\n            return location;\n        }\n        \n        @Override\n        public String toString() {\n            return \"ConfigurationSource{\" + \"location='\" + location +  '}';\n        }\n        \n        @Override\n        public boolean equals(final Object o) {\n            if (this == o) { return true; }\n            if (o == null || getClass() != o.getClass()) { return false; }\n            \n            final ConfigurationSource that = (ConfigurationSource) o;\n            \n            return getLocation() != null ? getLocation().equals(that.getLocation()) : that.getLocation() == null;\n        }\n        \n        @Override\n        public int hashCode() {\n            return getLocation() != null ? getLocation().hashCode() : 0;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/support/PropertiesLoader.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration.support;\n\nimport org.powermock.configuration.support.PropertiesFinder.ConfigurationSource;\nimport org.powermock.utils.StringJoiner;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Properties;\n\nclass PropertiesLoader {\n    Properties load(final String propertiesFile) {\n        if (propertiesFile == null) {\n            return null;\n        }\n        \n        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n        try {\n            final List<ConfigurationSource> configurations = new PropertiesFinder(classLoader).find(propertiesFile);\n            return loadProperties(configurations, propertiesFile);\n        } catch (Exception e) {\n            return null;\n        }\n    }\n    \n    private Properties loadProperties(final List<ConfigurationSource> configurations, final String propertiesFile) throws IOException {\n        if (configurations.size() == 0) {\n            return null;\n        } else {\n            if (configurations.size() > 1) {\n                printWarning(configurations, propertiesFile);\n            }\n            return loadPropertiesFromFile(configurations.get(0));\n        }\n    }\n    \n    private void printWarning(final List<ConfigurationSource> configurations, final String propertiesFile) {\n        System.err.printf(\n            \"Properties file %s is found in %s places: %s. Which one will be used is undefined. \" +\n                \"Please, remove duplicated configuration file (or second PowerMock jar file)\" +\n                \" from class path to have stable tests.\",\n            propertiesFile,\n            configurations.size(),\n            StringJoiner.join(configurations)\n        );\n    }\n    \n    private Properties loadPropertiesFromFile(final ConfigurationSource configurationSource) throws IOException {\n        final Properties properties = new Properties();\n        properties.load(configurationSource.inputStream());\n        return properties;\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/configuration/support/ValueAliases.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration.support;\n\nimport java.util.Map;\n\nclass ValueAliases {\n    private final Map<String, String> alias;\n    \n    ValueAliases(final Map<String, String> alias) {this.alias = alias;}\n    \n    String findValue(final String value) {\n        if (alias.containsKey(value)) {\n            return alias.get(value);\n        }\n        return value;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/ClassLocator.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\npublic class ClassLocator extends SecurityManager {\n    public static Class getCallerClass() {\n        return new ClassLocator().getClassContext()[5];\n    }\n}"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/ClassReplicaCreator.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport javassist.CannotCompileException;\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport javassist.CtConstructor;\nimport javassist.CtField;\nimport javassist.CtMethod;\nimport javassist.CtNewConstructor;\nimport javassist.CtNewMethod;\nimport javassist.Modifier;\nimport javassist.NotFoundException;\n\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicInteger;\n\n/**\n * This class takes care of creating a replica of a class. The class structure\n * is copied to the new class. This is useful in situations where you want to\n * create a mock for a class but it's not possible because of some restrictions\n * (such as the class being loaded by the bootstrap class-loader).\n */\npublic class ClassReplicaCreator {\n\n    private static final String POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME = \"powerMockInstanceDelegatorField\";\n    // Used to make each new replica class of a specific type unique.\n    private static AtomicInteger counter = new AtomicInteger(0);\n\n    public <T> Class<T> createClassReplica(Class<T> clazz) {\n        if (clazz == null) {\n            throw new IllegalArgumentException(\"clazz cannot be null\");\n        }\n        ClassPool classpool = ClassPool.getDefault();\n        final String originalClassName = clazz.getName();\n        CtClass originalClassAsCtClass;\n        final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz));\n        try {\n            originalClassAsCtClass = classpool.get(originalClassName);\n            CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods();\n            for (CtMethod ctMethod : declaredMethods) {\n                final String code = getReplicaMethodDelegationCode(clazz, ctMethod, null);\n                CtNewMethod.make(ctMethod.getReturnType(), ctMethod.getName(), ctMethod.getParameterTypes(), ctMethod.getExceptionTypes(),\n                        code, newClass);\n            }\n\n            return (Class<T>) newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain());\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n    /**\n     * Create a class that is a replica of type {@code T}. To allow for\n     * partial mocking all calls to non-mocked methods will be delegated to the\n     * {@code delegator}.\n     *\n     * @param <T>       The type of the replica class to be created.\n     * @param delegator The delegator object that will be invoked to allow for partial\n     *                  mocking.\n     * @return A replica class that can be used to duck-type an instance.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public <T> Class<T> createInstanceReplica(T delegator) {\n        if (delegator == null) {\n            throw new IllegalArgumentException(\"delegator cannot be null\");\n        }\n        final Class<T> clazz = (Class<T>) delegator.getClass();\n        ClassPool classpool = ClassPool.getDefault();\n        final String originalClassName = clazz.getName();\n        CtClass originalClassAsCtClass;\n        final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz));\n        try {\n            originalClassAsCtClass = classpool.get(originalClassName);\n\n            copyFields(originalClassAsCtClass, newClass);\n            addDelegatorField(delegator, newClass);\n\n            CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods();\n            for (CtMethod ctMethod : declaredMethods) {\n                @SuppressWarnings(\"unused\")\n                final String code = getReplicaMethodDelegationCode(delegator.getClass(), ctMethod, POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME);\n                CtMethod make2 = CtNewMethod.copy(ctMethod, newClass, null);\n                newClass.addMethod(make2);\n            }\n\n            CtConstructor[] declaredConstructors = originalClassAsCtClass.getDeclaredConstructors();\n            for (CtConstructor ctConstructor : declaredConstructors) {\n                CtConstructor copy = CtNewConstructor.copy(ctConstructor, newClass, null);\n                newClass.addConstructor(copy);\n            }\n            return (Class<T>) newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain());\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n    /**\n     * Add a field to the replica class that holds the instance delegator. I.e.\n     * if we're creating a instance replica of {@code java.lang.Long} this\n     * methods adds a new field of type {@code delegator.getClass()} to the\n     * replica class.\n     */\n    private <T> void addDelegatorField(T delegator, final CtClass replicaClass) throws CannotCompileException {\n        CtField f = CtField.make(String.format(\"private %s %s = null;\", delegator.getClass().getName(),\n                POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME), replicaClass);\n        replicaClass.addField(f);\n    }\n\n    private <T> String generateReplicaClassName(final Class<T> clazz) {\n        return \"replica.\" + clazz.getName() + \"$$PowerMock\" + counter.getAndIncrement();\n    }\n\n    private void copyFields(CtClass originalClassAsCtClass, final CtClass newClass) throws CannotCompileException, NotFoundException {\n        CtField[] declaredFields = originalClassAsCtClass.getDeclaredFields();\n        CtField[] undeclaredFields = originalClassAsCtClass.getFields();\n        Set<CtField> allFields = new HashSet<CtField>();\n        Collections.addAll(allFields, declaredFields);\n        Collections.addAll(allFields, undeclaredFields);\n\n        for (CtField ctField : allFields) {\n            CtField f = new CtField(ctField.getType(), ctField.getName(), newClass);\n            newClass.addField(f);\n        }\n    }\n\n    /*\n     * Invokes a instance method of the original instance. This enables partial\n     * mocking of system classes.\n     */\n    private String getReplicaMethodDelegationCode(Class<?> clazz, CtMethod ctMethod, String classOrInstanceToDelegateTo)\n            throws NotFoundException {\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"{java.lang.reflect.Method originalMethod = \");\n        builder.append(clazz.getName());\n        builder.append(\".class.getDeclaredMethod(\\\"\");\n        builder.append(ctMethod.getName());\n        builder.append(\"\\\", \");\n        final String parametersAsString = getParametersAsString(getParameterTypes(ctMethod));\n        if (\"\".equals(parametersAsString)) {\n            builder.append(\"null\");\n        } else {\n            builder.append(parametersAsString);\n        }\n        builder.append(\");\\n\");\n        builder.append(\"originalMethod.setAccessible(true);\\n\");\n        final CtClass returnType = ctMethod.getReturnType();\n        final boolean isVoid = returnType.equals(CtClass.voidType);\n        if (!isVoid) {\n            builder.append(\"return (\");\n            builder.append(returnType.getName());\n            builder.append(\") \");\n        }\n        builder.append(\"originalMethod.invoke(\");\n        if (Modifier.isStatic(ctMethod.getModifiers()) || classOrInstanceToDelegateTo == null) {\n            builder.append(clazz.getName());\n            builder.append(\".class\");\n        } else {\n            builder.append(classOrInstanceToDelegateTo);\n        }\n        builder.append(\", $args);}\");\n        return builder.toString();\n    }\n\n    private String[] getParameterTypes(CtMethod ctMethod) throws NotFoundException {\n        final CtClass[] parameterTypesAsCtClass = ctMethod.getParameterTypes();\n        final String[] parameterTypes = new String[parameterTypesAsCtClass.length];\n        for (int i = 0; i < parameterTypes.length; i++) {\n            parameterTypes[i] = parameterTypesAsCtClass[i].getName() + \".class\";\n        }\n        return parameterTypes;\n    }\n\n    private static String getParametersAsString(String[] types) {\n        StringBuilder parametersAsString = new StringBuilder();\n        if (types != null && types.length == 0) {\n            parametersAsString.append(\"new Class[0]\");\n        } else {\n            parametersAsString.append(\"new Class[] {\");\n            if (types != null) {\n                for (int i = 0; i < types.length; i++) {\n                    parametersAsString.append(types[i]);\n                    if (i != types.length - 1) {\n                        parametersAsString.append(\", \");\n                    }\n                }\n            }\n            parametersAsString.append(\"}\");\n        }\n        return parametersAsString.toString();\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/ConcreteClassGenerator.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport javassist.CtConstructor;\nimport javassist.CtMethod;\nimport javassist.CtNewMethod;\nimport javassist.Modifier;\nimport javassist.NotFoundException;\nimport org.powermock.reflect.internal.TypeUtils;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\n/**\n * This class takes care of creating a concrete sub-class implementing all\n * abstract methods in the parent.\n */\npublic class ConcreteClassGenerator {\n\n\t// Used to make each new subclass of a specific type unique.\n\tprivate static AtomicInteger counter = new AtomicInteger(0);\n\n\tpublic Class<?> createConcreteSubClass(Class<?> clazz) {\n\t\tif (clazz == null) {\n\t\t\tthrow new IllegalArgumentException(\"clazz cannot be null\");\n\t\t}\n\t\tif (!java.lang.reflect.Modifier.isAbstract(clazz.getModifiers())) {\n\t\t\tthrow new IllegalArgumentException(\"clazz must be abstract\");\n\t\t}\n\t\tClassPool classpool = ClassPool.getDefault();\n\t\tfinal String originalClassName = clazz.getName();\n\t\tfinal CtClass originalClassAsCtClass;\n\t\tfinal CtClass newClass = classpool.makeClass(generateClassName(clazz));\n\t\ttry {\n\t\t\tnewClass.setSuperclass(classpool.get(clazz.getName()));\n\t\t} catch (Exception e1) {\n\t\t\tthrow new RuntimeException(e1);\n\t\t}\n\t\ttry {\n\t\t\toriginalClassAsCtClass = classpool.get(originalClassName);\n\t\t\tCtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods();\n\t\t\tfor (CtMethod ctMethod : declaredMethods) {\n\t\t\t\tif (Modifier.isAbstract(ctMethod.getModifiers())) {\n\t\t\t\t\tfinal String code = getReturnCode(ctMethod.getReturnType());\n\t\t\t\t\tCtNewMethod.make(ctMethod.getReturnType(), ctMethod.getName(), ctMethod.getParameterTypes(),\n\t\t\t\t\t\t\tctMethod.getExceptionTypes(), code, newClass);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!hasInheritableConstructor(originalClassAsCtClass)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain());\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tprivate boolean hasInheritableConstructor(CtClass cls) throws NotFoundException {\n\t\tCtConstructor[] constructors = cls.getDeclaredConstructors();\n\t\tif (constructors.length == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tfor (CtConstructor ctConstructor : constructors) {\n\t\t\tint modifiers = ctConstructor.getModifiers();\n\t\t\tif (!Modifier.isPackage(modifiers) && !Modifier.isPrivate(modifiers)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\n\t}\n\n\tprivate String getReturnCode(CtClass returnType) {\n\t\tif (returnType.equals(CtClass.voidType)) {\n\t\t\treturn \"{}\";\n\t\t}\n\t\treturn \"{return \" + TypeUtils.getDefaultValueAsString(returnType.getName()) + \";}\";\n\t}\n\n\tprivate <T> String generateClassName(final Class<T> clazz) {\n\t\treturn \"subclass.\" + clazz.getName() + \"$$PowerMock\" + counter.getAndIncrement();\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/DefaultFieldValueGenerator.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.internal.TypeUtils;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.net.Inet4Address;\nimport java.net.InetAddress;\nimport java.util.Set;\n\n/**\n * Fills the fields with default not-null values. If a field type is an\n * interface a proxy returning default values for each method will be created.\n * If it's an abstract class a new concrete implementation of that type will\n * created and instantiated at run-time.\n * <p>\n * There are two scenarios where a field-type cannot possibly be assigned.\n * <ol>\n * <li>\n * When a class contains a field of it's own type, which would lead to infinite\n * recursion, {@code null} is assigned.</li>\n * <li>When the field type is an abstract Java system class with no visible\n * constructor (package-private) {@code null} is assigned.</li>\n * </ol>\n */\npublic class DefaultFieldValueGenerator {\n\n    public static <T> T fillWithDefaultValues(T object) {\n        if (object == null) {\n            throw new IllegalArgumentException(\"object to fill cannot be null\");\n        }\n        Set<Field> allInstanceFields = Whitebox.getAllInstanceFields(object);\n        for (Field field : allInstanceFields) {\n            final Class<?> fieldType = field.getType();\n            Object defaultValue = TypeUtils.getDefaultValue(fieldType);\n            if (defaultValue == null && fieldType != object.getClass() && !field.isSynthetic()) {\n                defaultValue = instantiateFieldType(field);\n                if (defaultValue != null) {\n                    fillWithDefaultValues(defaultValue);\n                }\n            }\n            try {\n                field.set(object, defaultValue);\n            } catch (Exception e) {\n                throw new RuntimeException(\"Internal error: Failed to set field.\", e);\n            }\n        }\n        return object;\n    }\n\n    private static Object instantiateFieldType(Field field) {\n        Class<?> fieldType = field.getType();\n        Object defaultValue;\n        int modifiers = fieldType.getModifiers();\n        if(fieldType.isAssignableFrom(ClassLoader.class) || isClass(fieldType)) {\n            defaultValue = null;\n        } else if (Modifier.isAbstract(modifiers) && !Modifier.isInterface(modifiers) && !fieldType.isArray()) {\n            Class<?> createConcreteSubClass = new ConcreteClassGenerator().createConcreteSubClass(fieldType);\n            defaultValue = createConcreteSubClass == null ? null : Whitebox.newInstance(createConcreteSubClass);\n        } else {\n            fieldType = substituteKnownProblemTypes(fieldType);\n            defaultValue = Whitebox.newInstance(fieldType);\n        }\n        return defaultValue;\n    }\n\n    private static boolean isClass(Class<?> fieldType) {\n        return fieldType == Class.class;\n    }\n\n    /**\n     * Substitute class types that are known to cause problems when generating\n     * them.\n     *\n     * @param fieldType the field type.\n     * @return A field-type substitute or the original class.\n     */\n    private static Class<?> substituteKnownProblemTypes(Class<?> fieldType) {\n        /*\n           * InetAddress has a private constructor and is normally not\n           * constructable without reflection. It's no problem instantiating this\n           * class using reflection or with Whitebox#newInstance but the problem\n           * lies in the equals method since it _always_ returns false even though\n           * it's the same instance! So in cases where classes containing an\n           * InetAddress field and uses it in the equals method (such as\n           * java.net.URL) then may return false since InetAddress#equals()\n           * returns false all the time. As a work-around we return an\n           * Inet4Address instead which has a proper equals method.\n           */\n        if (fieldType == InetAddress.class) {\n            return Inet4Address.class;\n        }\n        return fieldType;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/IdentityHashSet.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport java.util.AbstractSet;\nimport java.util.Iterator;\nimport java.util.Map;\n\npublic class IdentityHashSet<E> extends AbstractSet<E> {\n\n    protected final Map<E, Boolean> backedMap;\n\n    public IdentityHashSet() {\n        this.backedMap = new ListMap<E, Boolean>();\n    }\n\n    @Override\n    public int size() {\n        return backedMap.size();\n    }\n\n    @Override\n    public boolean contains(Object o) {\n        return backedMap.containsKey(o);\n    }\n\n    @Override\n    public boolean add(E o) {\n        return backedMap.put(o, Boolean.TRUE) == null;\n    }\n\n    @Override\n    public Iterator<E> iterator() {\n        return backedMap.keySet().iterator();\n    }\n\n    @Override\n    public boolean remove(Object o) {\n        return backedMap.remove(o) != null;\n    }\n\n    @Override\n    public void clear() {\n        backedMap.clear();\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/IndicateReloadClass.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\npublic class IndicateReloadClass {\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/InvocationException.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core;\n\npublic class InvocationException extends RuntimeException {\n    public InvocationException(final Throwable cause) {\n        super(cause);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/ListMap.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class ListMap<K, V> implements Map<K, V> {\n\n    private List<Map.Entry<K, V>> entries = new LinkedList<Entry<K, V>>();\n\n    private static class SimpleEntry<K, V> implements Entry<K, V> {\n\n        private K key;\n        private V value;\n\n        public SimpleEntry(K key, V value) {\n            this.key = key;\n            this.value = value;\n        }\n\n        @Override\n        public K getKey() {\n            return key;\n        }\n\n        @Override\n        public V getValue() {\n            return value;\n        }\n\n        @Override\n        public V setValue(V value) {\n            V old = this.value;\n            this.value = value;\n            return old;\n        }\n\n    }\n\n    @Override\n    public V remove(Object key) {\n        for (Iterator<Map.Entry<K, V>> i = entries.iterator(); i.hasNext();) {\n            Map.Entry<K, V> entry = i.next();\n            if (entry.getKey() == key) {\n                i.remove();\n                return entry.getValue();\n            }\n        }\n        return null;\n    }\n\n    @Override\n    public void clear() {\n        entries.clear();\n    }\n\n    @Override\n    public V get(Object key) {\n        for (Entry<K, V> entry : entries) {\n            if (entry.getKey() == key) {\n                return entry.getValue();\n            }\n        }\n        return null;\n    }\n\n    @Override\n    public V put(K key, V value) {\n        for (Entry<K, V> entry : entries) {\n            if (entry.getKey() == key) {\n                return entry.setValue(value);\n            }\n        }\n        Map.Entry<K, V> entry = new SimpleEntry<K, V>(key, value);\n        entries.add(entry);\n        return null;\n    }\n\n    @Override\n    public boolean containsKey(Object key) {\n        return get(key) != null;\n    }\n\n    @Override\n    public boolean containsValue(Object value) {\n        for (Entry<K, V> entry : entries) {\n            if (entry.getValue() == value) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    @Override\n    public Set<java.util.Map.Entry<K, V>> entrySet() {\n        throw new UnsupportedOperationException();\n    }\n\n    @Override\n    public boolean isEmpty() {\n        return entries.isEmpty();\n    }\n\n    @Override\n    public Set<K> keySet() {\n        Set<K> identityHashSet = new HashSet<K>();\n        for (Map.Entry<K, V> entry : entries) {\n            identityHashSet.add(entry.getKey());\n        }\n        return identityHashSet;\n    }\n\n    @Override\n    @SuppressWarnings(\"unchecked\")\n    public void putAll(Map<? extends K, ? extends V> t) {\n        Set<?> entrySet = t.entrySet();\n        for (Object object : entrySet) {\n            entries.add((java.util.Map.Entry<K, V>) object);\n        }\n    }\n\n    @Override\n    public int size() {\n        return entries.size();\n    }\n\n    @Override\n    public Collection<V> values() {\n        Set<V> hashSet = new HashSet<V>();\n        for (Map.Entry<K, V> entry : entries) {\n            hashSet.add(entry.getValue());\n        }\n        return hashSet;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/MockGateway.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport org.powermock.core.spi.MethodInvocationControl;\nimport org.powermock.core.spi.NewInvocationControl;\nimport org.powermock.reflect.internal.TypeUtils;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Modifier;\n\n/**\n * All mock invocations are routed through this gateway. This includes method\n * calls, construction of new instances and more. Do not use this class\n * directly, but always go through the PowerMock facade.\n */\npublic class MockGateway {\n\n    /**\n     * {@link #noMockito} is wrapped into it's own static class to make sure it is initialized not earlier than\n     * {@link #calledFromMockito()} is called for the first time.\n     */\n    private static final class NoMockito {\n        static final boolean noMockito = Package.getPackage(\"org.mockito\") == null;\n        private NoMockito() {}\n    }\n    public static final Object PROCEED = new Object();\n    public static final Object SUPPRESS = new Object();\n\n    /**\n     * Used to tell the MockGateway that the next call should not be mocked\n     * regardless if a {@link MethodInvocationControl} is found in the\n     * {@link MockRepository}. Used to allow for e.g. recursive partial mocking.\n     */\n    public static final String DONT_MOCK_NEXT_CALL = \"DontMockNextCall\";\n\n    /**\n     * Tells PowerMock to mock standard methods. These are\n     * {@link Object#toString()}, {@link Object#hashCode()} and\n     * {@link Object#equals(Object)}. By default this is {@code true}.\n     */\n    public static boolean MOCK_STANDARD_METHODS = true;\n\n    @SuppressWarnings(\"UnusedDeclaration\")\n    public static Object newInstanceCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {\n        final NewInvocationControl<?> newInvocationControl = MockRepository.getNewInstanceControl(type);\n        if (newInvocationControl != null) {\n            /*\n            * We need to deal with inner, local and anonymous inner classes\n            * specifically. For example when new is invoked on an inner class\n            * it seems like null is passed as an argument even though it\n            * shouldn't. We correct this here.\n            *\n            * Seems with Javassist 3.17.1-GA & Java 7, the 'null' is passed as the last argument.\n            */\n            if (type.isMemberClass() && Modifier.isStatic(type.getModifiers())) {\n                if (args.length > 0\n                        && ((args[0] == null && sig[0].getCanonicalName() == null)\n                        || (args[args.length - 1] == null && sig[args.length - 1].getCanonicalName() == null))\n                        && sig.length > 0) {\n                    args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], false);\n                }\n            } else if (type.isLocalClass() || type.isAnonymousClass() || type.isMemberClass()) {\n                if (args.length > 0 && sig.length > 0 && sig[0].equals(type.getEnclosingClass())) {\n                    args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], true);\n                }\n            }\n            return newInvocationControl.invoke(type, args, sig);\n        }\n        // Check if we should suppress the constructor code\n        if (MockRepository.shouldSuppressConstructor(WhiteboxImpl.getConstructor(type, sig))) {\n            return WhiteboxImpl.getFirstParentConstructor(type);\n        }\n        return PROCEED;\n    }\n\n    @SuppressWarnings(\"UnusedDeclaration\")\n    public static Object fieldCall(Object instanceOrClassContainingTheField, Class<?> classDefiningField,\n                                   String fieldName, Class<?> fieldType) {\n        if (MockRepository.shouldSuppressField(WhiteboxImpl.getField(classDefiningField, fieldName))) {\n            return TypeUtils.getDefaultValue(fieldType);\n        }\n        return PROCEED;\n    }\n\n    public static Object staticConstructorCall(String className) {\n        if (MockRepository.shouldSuppressStaticInitializerFor(className)) {\n            return \"suppress\";\n        }\n        return PROCEED;\n    }\n\n    @SuppressWarnings(\"UnusedDeclaration\")\n    public static Object constructorCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {\n        final Constructor<?> constructor = WhiteboxImpl.getConstructor(type, sig);\n        if (MockRepository.shouldSuppressConstructor(constructor)) {\n            return null;\n        }\n        return PROCEED;\n    }\n    \n    public static boolean suppressConstructorCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {\n        return constructorCall(type, args, sig) != PROCEED;\n    }\n\n    /**\n     * Tells PowerMock whether or not to mock\n     * {@link java.lang.Object#getClass()}.\n     */\n    public static boolean MOCK_GET_CLASS_METHOD = false;\n\n    /**\n     * Tells PowerMock whether or not to mock\n     * {@link java.lang.Class#isAnnotationPresent(Class)} and\n     * {@link java.lang.Class#getAnnotation(Class)}.\n     */\n    public static boolean MOCK_ANNOTATION_METHODS = false;\n\n    // used for instance methods\n    @SuppressWarnings(\"UnusedDeclaration\")\n    public static Object methodCall(Object instance, String methodName, Object[] args, Class<?>[] sig,\n                                    String returnTypeAsString) throws Throwable {\n        return doMethodCall(instance, methodName, args, sig, returnTypeAsString);\n    }\n\n    // used for static methods\n    @SuppressWarnings(\"UnusedDeclaration\")\n    public static Object methodCall(Class<?> type, String methodName, Object[] args, Class<?>[] sig,\n                                    String returnTypeAsString) throws Throwable {\n        return doMethodCall(type, methodName, args, sig, returnTypeAsString);\n    }\n\n\n    private static Object doMethodCall(Object object, String methodName, Object[] args, Class<?>[] sig,\n                                       String returnTypeAsString) throws Throwable {\n        if (!shouldMockMethod(methodName, sig)) {\n            return PROCEED;\n        }\n\n        MockInvocation mockInvocation = new MockInvocation(object, methodName, sig);\n        MethodInvocationControl methodInvocationControl = mockInvocation.getMethodInvocationControl();\n        Object returnValue = null;\n\n        // The following describes the equals non-static method.\n\n        if (isEqualsMethod(mockInvocation) && !isStaticMethod(mockInvocation)) {\n            returnValue = tryHandleEqualsMethod(mockInvocation);\n        }\n\n        if (returnValue != null) {\n            return returnValue;\n        }\n        return doMethodCall(object, args, returnTypeAsString, mockInvocation, methodInvocationControl);\n    }\n\n    private static Object doMethodCall(Object object, Object[] args,\n                                       String returnTypeAsString,\n                                       MockInvocation mockInvocation,\n                                       MethodInvocationControl methodInvocationControl) throws Throwable {\n        Object returnValue;\n\n        // At first should be checked that method not suppressed/stubbed, because otherwise for spies real\n        // method is involved.\n        // https://github.com/jayway/powermock/issues/327\n\n        if (MockRepository.shouldSuppressMethod(mockInvocation.getMethod(), mockInvocation.getObjectType())) {\n            returnValue = TypeUtils.getDefaultValue(returnTypeAsString);\n        } else if (MockRepository.shouldStubMethod(mockInvocation.getMethod())) {\n            returnValue = MockRepository.getMethodToStub(mockInvocation.getMethod());\n        } else if (methodInvocationControl != null && methodInvocationControl.isMocked(mockInvocation.getMethod()) && shouldMockThisCall()) {\n            returnValue = methodInvocationControl.invoke(object, mockInvocation.getMethod(), args);\n            if (returnValue == SUPPRESS) {\n                returnValue = TypeUtils.getDefaultValue(returnTypeAsString);\n            }\n        } else if (MockRepository.hasMethodProxy(mockInvocation.getMethod())) {\n                /*\n                 * We must temporary remove the method proxy when invoking the\n                 * invocation handler because if the invocation handler delegates\n                 * the call we will end up here again and we'll get a\n                 * StackOverflowError.\n                 */\n            final InvocationHandler invocationHandler = MockRepository.removeMethodProxy(mockInvocation.getMethod());\n            try {\n                returnValue = invocationHandler.invoke(object, mockInvocation.getMethod(), args);\n            } finally {\n                // Set the method proxy again after the invocation\n                MockRepository.putMethodProxy(mockInvocation.getMethod(), invocationHandler);\n            }\n        } else {\n            returnValue = PROCEED;\n        }\n        return returnValue;\n    }\n\n    /*\n     * Method handles exception cases with equals method.\n     */\n    private static Object tryHandleEqualsMethod(MockInvocation mockInvocation) {\n\n        // Fix for Issue http://code.google.com/p/powermock/issues/detail?id=88\n        // For some reason the method call to equals() on final methods is\n        // intercepted and during the further processing in Mockito the same\n        // equals() method is called on the same instance. A StackOverflowError\n        // is the result. The following fix changes this by checking if the\n        // method to be called is a final equals() method. In that case the\n        // original method is called by returning PROCEED.\n\n        if (mockInvocation.getMethod().getParameterTypes().length == 1\n                    && mockInvocation.getMethod().getParameterTypes()[0] == Object.class\n                    && Modifier.isFinal(mockInvocation.getMethod().getModifiers())) {\n            return PROCEED;\n        }\n\n        if (calledFromMockito()){\n            return PROCEED;\n        }\n\n        return null;\n    }\n\n\n    private static boolean isEqualsMethod(MockInvocation mockInvocation) {\n        return \"equals\".equals(mockInvocation.getMethod().getName());\n    }\n\n    private static boolean isStaticMethod(MockInvocation mockInvocation) {\n        return Modifier.isStatic(mockInvocation.getMethod().getModifiers());\n    }\n\n    private static boolean calledFromMockito() {\n        if (NoMockito.noMockito) {\n            return false;\n        }\n        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();\n        for (StackTraceElement stackTraceElement : stackTrace) {\n            if (stackTraceElement.getClassName().startsWith(\"org.mockito.\")){\n                return true;\n            }\n        }\n        return false;\n    }\n\n    private static boolean shouldMockMethod(String methodName, Class<?>[] sig) {\n        if (isJavaStandardMethod(methodName, sig) && !MOCK_STANDARD_METHODS) {\n            return false;\n        } else if (isGetClassMethod(methodName, sig) && !MOCK_GET_CLASS_METHOD) {\n            return false;\n        } else { return !(isAnnotationMethod(methodName, sig) && !MOCK_ANNOTATION_METHODS); }\n    }\n\n    private static boolean isJavaStandardMethod(String methodName, Class<?>[] sig) {\n        return (methodName.equals(\"equals\") && sig.length == 1) || (methodName.equals(\"hashCode\") && sig.length == 0)\n                       || (methodName.equals(\"toString\") && sig.length == 0);\n    }\n\n    private static boolean isGetClassMethod(String methodName, Class<?>[] sig) {\n        return methodName.equals(\"getClass\") && sig.length == 0;\n    }\n\n    private static boolean isAnnotationMethod(String methodName, Class<?>[] sig) {\n        return (methodName.equals(\"isAnnotationPresent\") && sig.length == 1) || (methodName.equals(\"getAnnotation\") && sig.length == 1);\n    }\n\n    private static boolean shouldMockThisCall() {\n        Object shouldSkipMockingOfNextCall = MockRepository.getAdditionalState(DONT_MOCK_NEXT_CALL);\n        final boolean shouldMockThisCall = shouldSkipMockingOfNextCall == null;\n        MockRepository.removeAdditionalState(DONT_MOCK_NEXT_CALL);\n        return shouldMockThisCall;\n    }\n\n    /**\n     * The first parameter of an inner, local or anonymous inner class is\n     * {@code null} or the enclosing instance. This should not be included\n     * in the substitute invocation since it is never expected by the user.\n     * <p/>\n     * Seems with Javassist 3.17.1-GA & Java 7, the '{@code null}' is passed as the last argument.\n     */\n    private static Object[] copyArgumentsForInnerOrLocalOrAnonymousClass(Object[] args, Class<?> sig,\n                                                                         boolean excludeEnclosingInstance) {\n        Object[] newArgs = new Object[args.length - 1];\n        final int start;\n        final int end;\n        int j = 0;\n\n        if ((args[0] == null && sig == null)|| excludeEnclosingInstance) {\n            start = 1;\n            end = args.length;\n        } else {\n            start = 0;\n            end = args.length - 1;\n        }\n\n        for (int i = start; i < end; i++) {\n            newArgs[j++] = args[i];\n        }\n        args = newArgs;\n        return args;\n    }\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/MockInvocation.java",
    "content": "package org.powermock.core;\n\nimport org.powermock.core.spi.MethodInvocationControl;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport org.powermock.reflect.internal.proxy.UnproxiedType;\n\nimport java.lang.reflect.Method;\n\nclass MockInvocation {\n    private Object object;\n    private String methodName;\n    private Class<?>[] sig;\n    private Class<?> objectType;\n    private MethodInvocationControl methodInvocationControl;\n    private Method method;\n    \n    MockInvocation(Object object, String methodName, Class<?>... sig) {\n        this.object = object;\n        this.methodName = methodName;\n        this.sig = sig;\n        init();\n    }\n    \n    private void init() {\n        if (object instanceof Class<?>) {\n            objectType = (Class<?>) object;\n            methodInvocationControl = MockRepository.getStaticMethodInvocationControl(objectType);\n        } else {\n            final Class<?> type = object.getClass();\n            UnproxiedType unproxiedType = WhiteboxImpl.getUnproxiedType(type);\n            objectType = unproxiedType.getOriginalType();\n            methodInvocationControl = MockRepository.getInstanceMethodInvocationControl(object);\n        }\n        method = findMethodToInvoke(methodName, sig, objectType);\n    }\n    \n    Class<?> getObjectType() {\n        return objectType;\n    }\n    \n    MethodInvocationControl getMethodInvocationControl() {\n        return methodInvocationControl;\n    }\n    \n    Method getMethod() {\n        return method;\n    }\n    \n    private static Method findMethodToInvoke(String methodName, Class<?>[] sig, Class<?> objectType) {\n        /*\n        * if invocationControl is null or the method is not mocked, invoke\n        * original method or suppress the method code otherwise invoke the\n        * invocation handler.\n        */\n        Method method;\n        try {\n            method = WhiteboxImpl.getBestMethodCandidate(objectType, methodName, sig, true);\n        } catch (MethodNotFoundException e) {\n            /*\n             * Dirty hack to get around issue 110\n             * (http://code.google.com/p/powermock/issues/detail?id=110). Review\n             * this! What we do here is to try to find a reflective method on\n             * class. This has begun to fail since version 1.2 when we supported\n             * mocking static methods in system classes.\n             */\n            try {\n                method = WhiteboxImpl.getMethod(Class.class, methodName, sig);\n            } catch (MethodNotFoundException e2) {\n                throw e;\n            }\n        }\n        return method;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/MockRepository.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport org.powermock.core.spi.MethodInvocationControl;\nimport org.powermock.core.spi.NewInvocationControl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Hold mock objects that should be used instead of the concrete implementation.\n * Mock transformers may use this class to gather information on which classes\n * and methods that are mocked.\n */\npublic class MockRepository {\n\n\tprivate static Set<Object> objectsToAutomaticallyReplayAndVerify = new IdentityHashSet<Object>();\n\n\tprivate static Map<Class<?>, NewInvocationControl<?>> newSubstitutions = new HashMap<Class<?>, NewInvocationControl<?>>();\n\n\t/**\n\t * Holds info about general method invocation mocks for classes.\n\t */\n\tprivate static Map<Class<?>, MethodInvocationControl> classMocks = new HashMap<Class<?>, MethodInvocationControl>();\n\n\t/**\n\t * Holds info about general method invocation mocks for instances.\n\t */\n\tprivate static Map<Object, MethodInvocationControl> instanceMocks = new ListMap<Object, MethodInvocationControl>();\n\n\t/**\n\t * Holds info about which methods that should return a substitute/another\n\t * instance instead of the default instance.\n\t */\n\tprivate static Map<Method, Object> substituteReturnValues = new HashMap<Method, Object>();\n\n\t/**\n\t * Holds info about which methods that are proxied.\n\t */\n\tprivate static Map<Method, InvocationHandler> methodProxies = new HashMap<Method, InvocationHandler>();\n\n\t/**\n\t * Holds info about which class that should have their static initializers\n\t * suppressed.\n\t */\n\tprivate static Set<String> suppressStaticInitializers = new HashSet<String>();\n\n\t/**\n\t * Sometimes mock frameworks needs to store additional state. They can do\n\t * this using this key/value based approach.\n\t */\n\tprivate static Map<String, Object> additionalState = new HashMap<String, Object>();\n\n\t/**\n\t * Set of constructors that should be suppressed.\n\t */\n\tprivate static final Set<Constructor<?>> suppressConstructor = new HashSet<Constructor<?>>();\n\n\t/**\n\t * Set of methods that should be suppressed.\n\t */\n\tprivate static final Set<Method> suppressMethod = new HashSet<Method>();\n\n\t/**\n\t * Set of methods that should be suppressed.\n\t */\n\tprivate static final Set<Field> suppressField = new HashSet<Field>();\n\n\t/**\n\t * Set of field types that should always be suppressed regardless of\n\t * instance.\n\t */\n\tprivate static final Set<String> suppressFieldTypes = new HashSet<String>();\n\n    /**\n     * Set of runnables that will be executed after the test (method) is completed.\n\t */\n\tprivate static final Set<Runnable> afterMethodRunners = new HashSet<Runnable>();\n\n\t/**\n\t * Clear all state of the mock repository except for static initializers.\n\t * The reason for not clearing static initializers is that when running in a\n\t * suite with many tests the clear method is invoked after each test. This\n\t * means that before the test that needs to suppress the static initializer\n\t * has been reach the state of the MockRepository would have been wiped out.\n\t * This is generally not a problem because most state will be added again\n\t * but suppression of static initializers are different because this state\n\t * can only be set once per class per CL. That's why we cannot remove this\n\t * state.\n\t */\n\tpublic synchronized static void clear() {\n\t\tnewSubstitutions.clear();\n\t\tclassMocks.clear();\n\t\tinstanceMocks.clear();\n\t\tobjectsToAutomaticallyReplayAndVerify.clear();\n\t\tadditionalState.clear();\n\t\tsuppressConstructor.clear();\n\t\tsuppressMethod.clear();\n\t\tsubstituteReturnValues.clear();\n\t\tsuppressField.clear();\n\t\tsuppressFieldTypes.clear();\n\t\tmethodProxies.clear();\n        for (Runnable runnable : afterMethodRunners) {\n            runnable.run();\n        }\n        afterMethodRunners.clear();\n\t}\n\n\t/**\n\t * Removes an object from the MockRepository if it exists.\n\t */\n\tpublic static void remove(Object mock) {\n\t\tif (mock instanceof Class<?>) {\n\t\t\tif (newSubstitutions.containsKey(mock)) {\n\t\t\t\tnewSubstitutions.remove(mock);\n\t\t\t}\n\t\t\tif (classMocks.containsKey(mock)) {\n\t\t\t\tclassMocks.remove(mock);\n\t\t\t}\n\t\t} else if (instanceMocks.containsKey(mock)) {\n\t\t\tinstanceMocks.remove(mock);\n\t\t}\n\t}\n\n\tpublic static synchronized MethodInvocationControl getStaticMethodInvocationControl(Class<?> type) {\n\t\treturn classMocks.get(type);\n\t}\n\n\tpublic static synchronized MethodInvocationControl putStaticMethodInvocationControl(Class<?> type, MethodInvocationControl invocationControl) {\n\t\treturn classMocks.put(type, invocationControl);\n\t}\n\n\tpublic static synchronized MethodInvocationControl removeClassMethodInvocationControl(Class<?> type) {\n\t\treturn classMocks.remove(type);\n\t}\n\n\tpublic static synchronized MethodInvocationControl getInstanceMethodInvocationControl(Object instance) {\n\t\treturn instanceMocks.get(instance);\n\t}\n\n\tpublic static synchronized MethodInvocationControl putInstanceMethodInvocationControl(Object instance, MethodInvocationControl invocationControl) {\n\t\treturn instanceMocks.put(instance, invocationControl);\n\t}\n\n\tpublic static synchronized MethodInvocationControl removeInstanceMethodInvocationControl(Class<?> type) {\n\t\treturn classMocks.remove(type);\n\t}\n\n\tpublic static synchronized NewInvocationControl<?> getNewInstanceControl(Class<?> type) {\n\t\treturn newSubstitutions.get(type);\n\t}\n\n\tpublic static synchronized NewInvocationControl<?> putNewInstanceControl(Class<?> type, NewInvocationControl<?> control) {\n\t\treturn newSubstitutions.put(type, control);\n\t}\n\n\t/**\n\t * Add a fully qualified class name for a class that should have its static\n\t * initializers suppressed.\n\t * \n\t * @param className\n\t *            The fully qualified class name for a class that should have\n\t *            its static initializers suppressed.\n\t */\n\tpublic static synchronized void addSuppressStaticInitializer(String className) {\n\t\tsuppressStaticInitializers.add(className);\n\t}\n\n\t/**\n\t * Remove a fully qualified class name for a class that should no longer\n\t * have its static initializers suppressed.\n\t * \n\t * @param className\n\t *            The fully qualified class name for a class that should no\n\t *            longer have its static initializers suppressed.\n\t */\n\tpublic static synchronized void removeSuppressStaticInitializer(String className) {\n\t\tsuppressStaticInitializers.remove(className);\n\t}\n\n\t/**\n\t * Check whether or not a class with the fully qualified name should have\n\t * its static initializers suppressed.\n\t * \n\t * @param className\n\t *            {@code true} if class with the fully qualified name\n\t *            {@code className} should have its static initializers\n\t *            suppressed, {@code false} otherwise.\n\t */\n\tpublic static synchronized boolean shouldSuppressStaticInitializerFor(String className) {\n\t\treturn suppressStaticInitializers.contains(className);\n\t}\n\n\t/**\n\t * @return All classes that should be automatically replayed or verified.\n\t */\n\tpublic static synchronized Set<Object> getObjectsToAutomaticallyReplayAndVerify() {\n\t\treturn Collections.unmodifiableSet(objectsToAutomaticallyReplayAndVerify);\n\t}\n\n\t/**\n\t * Add classes that should be automatically replayed or verified.\n\t */\n\tpublic static synchronized void addObjectsToAutomaticallyReplayAndVerify(Object... objects) {\n\t\tCollections.addAll(objectsToAutomaticallyReplayAndVerify, objects);\n\t}\n\n\t/**\n\t * When a mock framework API needs to store additional state not applicable\n\t * for the other methods, it may use this method to do so.\n\t * \n\t * @param key\n\t *            The key under which the <tt>value</tt> is stored.\n\t * @param value\n\t *            The value to store under the specified <tt>key</tt>.\n\t * @return The previous object under the specified <tt>key</tt> or\n\t *         {@code null}.\n\t */\n\tpublic static synchronized Object putAdditionalState(String key, Object value) {\n\t\treturn additionalState.put(key, value);\n\t}\n\n\tpublic static synchronized Object removeAdditionalState(String key) {\n\t\treturn additionalState.remove(key);\n\t}\n\n\tpublic static synchronized InvocationHandler removeMethodProxy(Method method) {\n\t\treturn methodProxies.remove(method);\n\t}\n\n\t/**\n\t * Retrieve state based on the supplied key.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static synchronized <T> T getAdditionalState(String key) {\n\t\treturn (T) additionalState.get(key);\n\t}\n\n\t/**\n\t * Add a method to suppress.\n\t * \n\t * @param method\n\t *            The method to suppress.\n\t */\n\tpublic static synchronized void addMethodToSuppress(Method method) {\n\t\tsuppressMethod.add(method);\n\t}\n\n\t/**\n\t * Add a field to suppress.\n\t * \n\t * @param field\n\t *            The field to suppress.\n\t */\n\tpublic static synchronized void addFieldToSuppress(Field field) {\n\t\tsuppressField.add(field);\n\t}\n\n\t/**\n\t * Add a field type to suppress. All fields of this type will be suppressed.\n\t * \n\t * @param fieldType\n\t *            The fully-qualified name to a type. All fields of this type\n\t *            will be suppressed.\n\t */\n\tpublic static synchronized void addFieldTypeToSuppress(String fieldType) {\n\t\tsuppressFieldTypes.add(fieldType);\n\t}\n\n\t/**\n\t * Add a constructor to suppress.\n\t * \n\t * @param constructor\n\t *            The constructor to suppress.\n\t */\n\tpublic static synchronized void addConstructorToSuppress(Constructor<?> constructor) {\n\t\tsuppressConstructor.add(constructor);\n\t}\n\n\t/**\n\t * @return {@code true} if the <tt>method</tt> should be proxied.\n\t */\n\tpublic static synchronized boolean hasMethodProxy(Method method) {\n\t\treturn methodProxies.containsKey(method);\n\t}\n\n\t/**\n\t * @return {@code true} if the <tt>method</tt> should be suppressed.\n\t */\n\tpublic static synchronized boolean shouldSuppressMethod(Method method,\n\t\t\tClass<?> objectType) throws ClassNotFoundException {\n\t\tfor (Method suppressedMethod : suppressMethod) {\n\t\t\tClass<?> suppressedMethodClass = suppressedMethod\n\t\t\t\t\t.getDeclaringClass();\n\t\t\tif (suppressedMethodClass.getClass().isAssignableFrom(\n\t\t\t\t\tobjectType.getClass())\n\t\t\t\t\t&& suppressedMethod.getName().equals(method.getName())\n\t\t\t\t\t&& ClassLocator.getCallerClass().getName()\n\t\t\t\t\t\t\t.equals(suppressedMethodClass.getName())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return {@code true} if the <tt>field</tt> should be suppressed.\n\t */\n\tpublic static synchronized boolean shouldSuppressField(Field field) {\n\t\treturn suppressField.contains(field) || suppressFieldTypes.contains(field.getType().getName());\n\t}\n\n\t/**\n\t * @return {@code true} if the <tt>constructor</tt> should be\n\t *         suppressed.\n\t */\n\tpublic static synchronized boolean shouldSuppressConstructor(Constructor<?> constructor) {\n\t\treturn suppressConstructor.contains(constructor);\n\t}\n\n\t/**\n\t * @return {@code true} if the <tt>method</tt> has a substitute return\n\t *         value.\n\t */\n\tpublic static synchronized boolean shouldStubMethod(Method method) {\n\t\treturn substituteReturnValues.containsKey(method);\n\t}\n\n\t/**\n\t * @return The substitute return value for a particular method, may be\n\t *         {@code null}.\n\t */\n\tpublic static synchronized Object getMethodToStub(Method method) {\n\t\treturn substituteReturnValues.get(method);\n\t}\n\n\t/**\n\t * Set a substitute return value for a method. Whenever this method will be\n\t * called the {@code value} will be returned instead.\n\t * \n\t * @return The previous substitute value if any.\n\t */\n\tpublic static synchronized Object putMethodToStub(Method method, Object value) {\n\t\treturn substituteReturnValues.put(method, value);\n\t}\n\n\t/**\n\t * @return The proxy for a particular method, may be {@code null}.\n\t */\n\tpublic static synchronized InvocationHandler getMethodProxy(Method method) {\n\t\treturn methodProxies.get(method);\n\t}\n\n\t/**\n\t * Set a proxy for a method. Whenever this method is called the invocation\n\t * handler will be invoked instead.\n\t * \n\t * @return The method proxy if any.\n\t */\n\tpublic static synchronized InvocationHandler putMethodProxy(Method method, InvocationHandler invocationHandler) {\n\t\treturn methodProxies.put(method, invocationHandler);\n\t}\n\n    /**\n     * Add a {@link Runnable} that will be executed after each test\n     * @param runnable - an instance of {@link Runnable} that will be executed.\n     */\n    public static synchronized void addAfterMethodRunner(Runnable runnable) {\n        afterMethodRunners.add(runnable);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/PowerMockUtils.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport java.lang.reflect.Field;\nimport java.util.Iterator;\nimport java.util.Vector;\n\npublic class PowerMockUtils {\n\n\t/**\n\t * Get an iterator of all classes loaded by the specific classloader.\n\t * \n\t * @param classLoader  the class loader for that iterator with all loaded classes should be created.\n\t * @return the iterator with all classes loaded by the given {@code classLoader}\n\t * @throws NoSuchFieldException\n\t * @throws IllegalAccessException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static Iterator<Class<?>> getClassIterator(ClassLoader classLoader) throws NoSuchFieldException, IllegalAccessException {\n\t\tClass<?> classLoaderClass = classLoader.getClass();\n\t\twhile (classLoaderClass != ClassLoader.class) {\n\t\t\tclassLoaderClass = classLoaderClass.getSuperclass();\n\t\t}\n\t\tField classesField = classLoaderClass.getDeclaredField(\"classes\");\n\t\tclassesField.setAccessible(true);\n\t\tVector<Class<?>> classes = (Vector<Class<?>>) classesField.get(classLoader);\n\t\treturn classes.iterator();\n\t}\n\n\t/**\n\t * \n\t * @param classLoader the class loader for that classes is printed.\n\t * @throws NoSuchFieldException\n\t * @throws IllegalAccessException\n\t */\n\tpublic static void printClassesLoadedByClassloader(ClassLoader classLoader, boolean includeParent) throws NoSuchFieldException,\n\t\t\tIllegalAccessException {\n\t\twhile (classLoader != null) {\n\t\t\tSystem.out.println(\"ClassLoader: \" + classLoader);\n\t\t\tfor (Iterator<?> iter = PowerMockUtils.getClassIterator(classLoader); iter.hasNext();) {\n\t\t\t\tSystem.out.println(\"\\t\" + iter.next());\n\t\t\t}\n\t\t\tif (includeParent) {\n\t\t\t\tclassLoader = classLoader.getParent();\n\t\t\t} else {\n\t\t\t\tclassLoader = null;\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/WildcardMatcher.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core;\n\nimport java.util.Collection;\n\n/**\n * Wildcard matcher.\n */\npublic class WildcardMatcher {\n\n    private static final char WILDCARD = '*';\n\n    /**\n     * Performs a wildcard matching for the text and pattern provided.\n     * \n     * @param text\n     *            the text to be tested for matches.\n     * \n     * @param pattern\n     *            the pattern to be matched for. This can contain the wildcard\n     *            character '*' (asterisk).\n     * \n     * @return <tt>true</tt> if a match is found, <tt>false</tt> otherwise.\n     */\n    public static boolean matches(String text, String pattern) {\n        if (text == null) {\n            throw new IllegalArgumentException(\"text cannot be null\");\n        }\n\n        text += '\\0';\n        pattern += '\\0';\n\n        int N = pattern.length();\n\n        boolean[] states = new boolean[N + 1];\n        boolean[] old = new boolean[N + 1];\n        old[0] = true;\n\n        for (int i = 0; i < text.length(); i++) {\n            char c = text.charAt(i);\n            states = new boolean[N + 1]; // initialized to false\n            for (int j = 0; j < N; j++) {\n                char p = pattern.charAt(j);\n\n                // hack to handle *'s that match 0 characters\n                if (old[j] && (p == WILDCARD))\n                    old[j + 1] = true;\n\n                if (old[j] && (p == c))\n                    states[j + 1] = true;\n                if (old[j] && (p == WILDCARD))\n                    states[j] = true;\n                if (old[j] && (p == WILDCARD))\n                    states[j + 1] = true;\n            }\n            old = states;\n        }\n        return states[N];\n\n    }\n\n    public static boolean matchesAny(Collection<String> patterns, String text) {\n        for (String pattern : patterns) {\n            if (matches(text, pattern)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    public static boolean matchesAny(Iterable<String> patterns, String text) {\n        for (String string : patterns) {\n            if (matches(text, string)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    public static boolean matchesAny(String[] patterns, String text) {\n        for (String string : patterns) {\n            if (matches(text, string)) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/agent/JavaAgentClassRegister.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.agent;\n\n/**\n * This register contains information about which class has been modified by PowerMock Java Agent.\n */\npublic interface JavaAgentClassRegister {\n\n    /**\n     * Check if class with {@code className} has been modified for the given class loader\n     * @param classLoader - {@link ClassLoader} for that class should be checked\n     * @param className - name of class\n     * @return {@code true} if the given class has been modified, otherwise {@code false}\n     */\n    boolean isModifiedByAgent(ClassLoader classLoader, String className);\n\n    /**\n     * Register that the class with name {@code className} has been  modified for the given class loader.\n     * @param loader - {@link ClassLoader} for that class has been modified.\n     * @param className - name of the class which has been modified.\n     */\n    void registerClass(ClassLoader loader, String className);\n\n    /**\n     * Remove all registered classes for all class loaders.\n     */\n    void clear();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/agent/JavaAgentFrameworkRegister.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.agent;\n\n/**\n * Instance of class should set/clear an instance of the JavaAgentClassRegister\n * in Mockito Frameworks classes\n */\npublic interface JavaAgentFrameworkRegister {\n\n    /**\n     * Set the {@code javaAgentClassRegister} to current loaded mocking framework.\n     * @param javaAgentClassRegister - an instance of {@link JavaAgentClassRegister} which should be set to\n     *                               frameworks classes.\n     */\n    void set(JavaAgentClassRegister javaAgentClassRegister);\n\n    /**\n     * Remove all links to JavaAgentClassRegister\n     */\n    void clear();\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/agent/JavaAgentFrameworkRegisterFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.agent;\n\nimport org.powermock.reflect.Whitebox;\n\n/**\n * Factory to create an instance of JavaAgentFrameworkRegister,\n * depends on which mocking framework is loaded in runtime.\n */\npublic class JavaAgentFrameworkRegisterFactory {\n\n    public static JavaAgentFrameworkRegister create() {\n\n        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n\n        return getInstanceForClassLoader(classLoader);\n    }\n\n    private static JavaAgentFrameworkRegister getInstanceForClassLoader(ClassLoader classLoader) {\n        Class<JavaAgentFrameworkRegister> frameworkReporterClass = getJavaAgentFrameworkRegisterClass(classLoader);\n        return Whitebox.newInstance(frameworkReporterClass);\n    }\n    \n    @SuppressWarnings(\"unchecked\")\n    private static Class<JavaAgentFrameworkRegister> getJavaAgentFrameworkRegisterClass(ClassLoader classLoader) {\n        Class<JavaAgentFrameworkRegister> agentFrameworkRegisterClass;\n        try {\n            agentFrameworkRegisterClass = (Class<JavaAgentFrameworkRegister>) classLoader.loadClass(getImplementerClassName());\n        } catch (ClassNotFoundException e) {\n            throw new RuntimeException(e);\n        }\n        return agentFrameworkRegisterClass;\n    }\n    \n    @SuppressWarnings(\"SameReturnValue\")\n    private static String getImplementerClassName() {\n        return \"org.powermock.api.extension.agent.JavaAgentFrameworkRegisterImpl\";\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/bytebuddy/ConditionalStateStackManipulation.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.bytebuddy;\n\nimport net.bytebuddy.implementation.Implementation.Context;\nimport net.bytebuddy.implementation.bytecode.StackManipulation;\nimport net.bytebuddy.jar.asm.Label;\nimport net.bytebuddy.jar.asm.MethodVisitor;\nimport net.bytebuddy.jar.asm.Opcodes;\n\npublic class ConditionalStateStackManipulation implements StackManipulation {\n    \n    \n    private final StackManipulation condition;\n    private final StackManipulation action;\n    private final StackManipulation otherwise;\n    private final Frame frame;\n    \n    public ConditionalStateStackManipulation(final StackManipulation condition,\n                                             final StackManipulation action,\n                                             final StackManipulation otherwise,\n                                             final Frame frame) {\n        \n        this.condition = condition;\n        this.action = action;\n        this.otherwise = otherwise;\n        this.frame = frame;\n    }\n    \n    @Override\n    public boolean isValid() {\n        return true;\n    }\n    \n    @Override\n    public Size apply(final MethodVisitor mv, final Context implementationContext) {\n    \n        Size size = new Size(0, 0);\n        \n        Label proceed = new Label();\n        Label exit = new Label();\n    \n        size = size.aggregate(condition.apply(mv, implementationContext));\n    \n        mv.visitJumpInsn(Opcodes.IFEQ, proceed);\n    \n        size = size.aggregate(action.apply(mv, implementationContext));\n    \n        mv.visitJumpInsn(Opcodes.GOTO, exit);\n    \n        mv.visitLabel(proceed);\n        mv.visitFrame(Opcodes.F_FULL, frame.localSize(), frame.locals(), 0, null);\n    \n        size = size.aggregate(otherwise.apply(mv, implementationContext));\n        \n        mv.visitLabel(exit);\n    \n        mv.visitFrame(Opcodes.F_FULL, 0, null, 0, null);\n        \n        return size;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/bytebuddy/Frame.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.bytebuddy;\n\n\nimport net.bytebuddy.description.method.ParameterDescription;\nimport net.bytebuddy.description.method.ParameterDescription.InDefinedShape;\nimport net.bytebuddy.description.method.ParameterList;\nimport net.bytebuddy.description.type.TypeDescription.Generic;\nimport net.bytebuddy.implementation.bytecode.StackSize;\nimport net.bytebuddy.jar.asm.Opcodes;\nimport net.bytebuddy.utility.CompoundList;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Deque;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Frame {\n    \n    public static Frame beforeConstructorCall(final Iterable<? extends ParameterDescription> constructorParameters) {\n        List<LocalVariable> locals = new ArrayList<LocalVariable>();\n        \n        locals.add(LocalVariable.UNINITIALIZED_THIS);\n        \n        int maxLocals = 1;\n        \n        for (ParameterDescription sourceParameter : constructorParameters) {\n            Generic type = sourceParameter.getType();\n            locals.add(LocalVariable.from(type));\n            maxLocals += type.getStackSize().getSize();\n        }\n        \n        return new Frame(locals);\n    }\n    \n    private Deque<Object> stack;\n    private List<LocalVariable> locals;\n    \n    public Frame(final List<LocalVariable> locals) {\n        this.locals = Collections.unmodifiableList(locals);\n        this.stack = new LinkedList<Object>();\n    }\n    \n    public Frame addTopToLocals(final int count) {\n        List<LocalVariable> locals = new ArrayList<LocalVariable>();\n        for (int i = 0; i < count; i++) {\n            locals.add(LocalVariable.TOP);\n        }\n        \n        return new Frame(\n                            CompoundList.of(this.locals, locals)\n        );\n    }\n    \n    public Frame addLocalVariable(final LocalVariable localVariable) {\n        return new Frame(\n                            CompoundList.of(this.locals, localVariable)\n        );\n    }\n    \n    public Frame addLocalVariables(final ParameterList<InDefinedShape> types) {\n        \n        List<LocalVariable> frameLocals = new ArrayList<LocalVariable>();\n        \n        for (ParameterDescription parameter : types) {\n            Generic type = parameter.getType();\n            frameLocals.add(LocalVariable.from(type));\n        }\n        \n        return new Frame(CompoundList.of(this.locals, frameLocals));\n    }\n    \n    public Object[] locals() {\n        Object[] frameLocals = new Object[this.locals.size()];\n        for (int i = 0; i < this.locals.size(); i++) {\n            frameLocals[i] = this.locals.get(i).getType();\n        }\n        return frameLocals;\n    }\n    \n    public int localSize() {\n        return locals.size();\n    }\n    \n    public int maxLocalVariableIndex() {\n        int localStackSize = 0;\n        for (LocalVariable localVariable : locals) {\n            localStackSize += localVariable.getStackSize().getSize();\n        }\n        return localStackSize;\n    }\n    \n    public static class LocalVariable {\n        public static LocalVariable from(final Generic type) {\n            if (type.represents(double.class)) {\n                return DOUBLE;\n            } else {\n                return new LocalVariable(\n                    type.getTypeName().replace('.', '/'),\n                    type.getStackSize()\n                );\n            }\n        }\n        \n        public static final LocalVariable UNINITIALIZED_THIS = new LocalVariable(Opcodes.UNINITIALIZED_THIS, StackSize.SINGLE);\n        public static final LocalVariable TOP = new LocalVariable(Opcodes.TOP, StackSize.SINGLE);\n        public static final LocalVariable DOUBLE = new LocalVariable(Opcodes.DOUBLE, StackSize.DOUBLE);\n        \n        private final Object type;\n        private final StackSize stackSize;\n    \n        private LocalVariable(final Object type, StackSize size) {\n            this.type = type;\n            this.stackSize = size;\n        }\n        \n        public Object getType() {\n            return type;\n        }\n    \n        public StackSize getStackSize() {\n            return stackSize;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/bytebuddy/MaxLocalsExtractor.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.bytebuddy;\n\nimport net.bytebuddy.description.method.MethodDescription;\nimport net.bytebuddy.jar.asm.ClassVisitor;\nimport net.bytebuddy.jar.asm.MethodVisitor;\nimport net.bytebuddy.jar.asm.Opcodes;\n\npublic class MaxLocalsExtractor extends ClassVisitor {\n    \n    private MethodMaxLocals methodMaxLocals;\n    \n    public MaxLocalsExtractor() {\n        super(Opcodes.ASM5);\n    }\n    \n    @Override\n    public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature,\n                                     final String[] exceptions) {\n        if (MethodDescription.CONSTRUCTOR_INTERNAL_NAME.equals(name)) {\n            methodMaxLocals = new MethodMaxLocals();\n            return new MaxLocalsMethodVisitor(name, desc, methodMaxLocals);\n        }\n        return super.visitMethod(access, name, desc, signature, exceptions);\n    }\n    \n    public MethodMaxLocals getMethods() {\n        return methodMaxLocals;\n    }\n    \n    private static class MaxLocalsMethodVisitor extends MethodVisitor {\n        \n        private final String name;\n        private final String signature;\n        private final MethodMaxLocals methodMaxLocals;\n        private int maxLocals;\n        \n        private MaxLocalsMethodVisitor(final String name, final String signature,\n                                       final MethodMaxLocals methodMaxLocals) {\n            super(Opcodes.ASM5);\n            this.name = name;\n            this.signature = signature;\n            this.methodMaxLocals = methodMaxLocals;\n        }\n        \n        @Override\n        public void visitMaxs(final int maxStack, final int maxLocals) {\n            this.maxLocals = maxLocals;\n            super.visitMaxs(maxStack, maxLocals);\n        }\n        \n        @Override\n        public void visitEnd() {\n            methodMaxLocals.add(name, signature, maxLocals);\n            super.visitEnd();\n        }\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/bytebuddy/MethodMaxLocals.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.bytebuddy;\n\nimport net.bytebuddy.description.method.MethodDescription;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n\npublic class MethodMaxLocals {\n    \n    private final Map<String, Integer> methodMaxLocals;\n    \n    MethodMaxLocals() {\n        methodMaxLocals = new HashMap<String, Integer>();\n    }\n    \n    public void add(String name, String signature, int maxLocals) {\n        methodMaxLocals.put(name + signature, maxLocals);\n    }\n    \n    public int getMethodMaxLocal(final MethodDescription instrumentedMethod) {\n        final String key = instrumentedMethod.getInternalName() + instrumentedMethod.getDescriptor();\n        final Integer maxLocals = methodMaxLocals.get(key);\n        return maxLocals == null ? 0 : maxLocals;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/bytebuddy/MockGetawayCall.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.bytebuddy;\n\nimport net.bytebuddy.description.method.MethodDescription.ForLoadedMethod;\nimport net.bytebuddy.description.method.ParameterDescription.InDefinedShape;\nimport net.bytebuddy.description.method.ParameterList;\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.implementation.Implementation.Context;\nimport net.bytebuddy.implementation.bytecode.StackManipulation;\nimport net.bytebuddy.implementation.bytecode.collection.ArrayFactory;\nimport net.bytebuddy.implementation.bytecode.constant.ClassConstant;\nimport net.bytebuddy.implementation.bytecode.member.MethodInvocation;\nimport net.bytebuddy.jar.asm.MethodVisitor;\nimport org.powermock.core.bytebuddy.Variable.VariableAccess;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\npublic class MockGetawayCall {\n    \n    private final Method getawayMethod;\n    \n    public MockGetawayCall(final Class mockGetawayClass) {\n        getawayMethod = WhiteboxImpl.getMethod(\n            mockGetawayClass, \"suppressConstructorCall\", Class.class, Object[].class, Class[].class\n        );\n    }\n    \n    public ForType forType(final TypeDescription targetType) {\n        return new ForType(this, targetType);\n    }\n    \n    public static class ForType {\n        private final TypeDescription targetType;\n        private final MockGetawayCall mockGetawayCall;\n    \n        private ForType(final MockGetawayCall mockGetawayCall, final TypeDescription targetType) {\n            this.mockGetawayCall = mockGetawayCall;\n            this.targetType = targetType;\n        }\n        \n        \n        public WithArguments withArguments(final List<Variable> parameters) {\n            return new WithArguments(this, parameters);\n        }\n        \n    }\n    \n    public static class WithArguments {\n        private final ForType forType;\n        private final List<Variable> arguments;\n    \n        private WithArguments(final ForType forType, final List<Variable> arguments) {\n            this.forType = forType;\n            this.arguments = arguments;\n        }\n        \n        public ConstructorMockGetawayCall withParameterTypes(final ParameterList<InDefinedShape> targetParameters) {\n            return new ConstructorMockGetawayCall(\n                forType.mockGetawayCall.getawayMethod,\n                forType.targetType,\n                arguments,\n                targetParameters\n            );\n        }\n    }\n    \n    private static class ConstructorMockGetawayCall implements StackManipulation {\n        \n        private final Method getawayMethod;\n        private final TypeDescription targetType;\n        private final List<Variable> arguments;\n        private final ParameterList<InDefinedShape> targetParameters;\n    \n        private ConstructorMockGetawayCall(final Method getawayMethod,\n                                           final TypeDescription targetType,\n                                           final List<Variable> arguments,\n                                           final ParameterList<InDefinedShape> targetParameters\n        ) {\n            this.getawayMethod = getawayMethod;\n            this.targetType = targetType;\n            this.arguments = arguments;\n            this.targetParameters = targetParameters;\n        }\n        \n        private List<StackManipulation> loadSignatureParametersClasess() {\n            List<StackManipulation> constructorSignature = new ArrayList<StackManipulation>();\n            \n            for (InDefinedShape targetParameter : targetParameters) {\n                constructorSignature.add(\n                    ClassConstant.of(targetParameter.getType().asErasure())\n                );\n            }\n            return constructorSignature;\n        }\n        \n        private List<StackManipulation> loadArgumentsFromVariable() {\n            List<StackManipulation> loadTargetParameters = new ArrayList<StackManipulation>();\n            for (Variable argument : arguments) {\n                loadTargetParameters.add(\n                    VariableAccess.load(argument, true)\n                );\n            }\n            return loadTargetParameters;\n        }\n        \n        @Override\n        public boolean isValid() {\n            return true;\n        }\n        \n        \n        @Override\n        public Size apply(final MethodVisitor mv, final Context implementationContext) {\n            List<StackManipulation> loadTargetParameters = loadArgumentsFromVariable();\n            List<StackManipulation> constructorSignature = loadSignatureParametersClasess();\n            \n            return new Compound(\n                                   ClassConstant.of(targetType),\n                                   ArrayFactory.forType(TypeDescription.OBJECT.asGenericType()).withValues(loadTargetParameters),\n                                   ArrayFactory.forType(TypeDescription.CLASS.asGenericType()).withValues(constructorSignature),\n                                   MethodInvocation.invoke(new ForLoadedMethod(getawayMethod))\n            ).apply(mv, implementationContext);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/bytebuddy/PrimitiveBoxing.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.bytebuddy;\n\nimport net.bytebuddy.description.type.TypeDefinition;\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.description.type.TypeDescription.ForLoadedType;\nimport net.bytebuddy.implementation.Implementation;\nimport net.bytebuddy.implementation.bytecode.StackManipulation;\nimport net.bytebuddy.implementation.bytecode.StackSize;\nimport net.bytebuddy.jar.asm.MethodVisitor;\nimport net.bytebuddy.jar.asm.Opcodes;\n\npublic enum PrimitiveBoxing implements StackManipulation{\n    \n    BOOLEAN(Boolean.class, StackSize.ZERO, \"valueOf\", \"(Z)Ljava/lang/Boolean;\"),\n    \n    BYTE(Byte.class, StackSize.ZERO, \"valueOf\", \"(B)Ljava/lang/Byte;\"),\n    \n    SHORT(Short.class, StackSize.ZERO, \"valueOf\", \"(S)Ljava/lang/Short;\"),\n    \n    CHARACTER(Character.class, StackSize.ZERO, \"valueOf\", \"(C)Ljava/lang/Character;\"),\n    \n    INTEGER(Integer.class, StackSize.ZERO, \"valueOf\", \"(I)Ljava/lang/Integer;\"),\n    \n    LONG(Long.class, StackSize.SINGLE, \"valueOf\", \"(J)Ljava/lang/Long;\"),\n    \n    FLOAT(Float.class, StackSize.ZERO, \"valueOf\", \"(F)Ljava/lang/Float;\"),\n    \n    DOUBLE(Double.class, StackSize.SINGLE, \"valueOf\", \"(D)Ljava/lang/Double;\");\n    \n    private final ForLoadedType wrapperType;\n    private final Size size;\n    private final String boxingMethodName;\n    private final String boxingMethodDescriptor;\n    \n    PrimitiveBoxing(Class<?> wrapperType,\n                    StackSize sizeDifference,\n                    String boxingMethodName,\n                    String boxingMethodDescriptor) {\n        this.wrapperType = new TypeDescription.ForLoadedType(wrapperType);\n        this.size = sizeDifference.toDecreasingSize();\n        this.boxingMethodName = boxingMethodName;\n        this.boxingMethodDescriptor = boxingMethodDescriptor;\n    }\n    \n    public static PrimitiveBoxing forPrimitive(TypeDefinition typeDefinition) {\n        if (typeDefinition.represents(boolean.class)) {\n            return BOOLEAN;\n        } else if (typeDefinition.represents(byte.class)) {\n            return BYTE;\n        } else if (typeDefinition.represents(short.class)) {\n            return SHORT;\n        } else if (typeDefinition.represents(char.class)) {\n            return CHARACTER;\n        } else if (typeDefinition.represents(int.class)) {\n            return INTEGER;\n        } else if (typeDefinition.represents(long.class)) {\n            return LONG;\n        } else if (typeDefinition.represents(float.class)) {\n            return FLOAT;\n        } else if (typeDefinition.represents(double.class)) {\n            return DOUBLE;\n        } else {\n            throw new IllegalArgumentException(\"Not a non-void, primitive type: \" + typeDefinition);\n        }\n    }\n    \n    @Override\n    public boolean isValid() {\n        return true;\n    }\n    \n    @Override\n    public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {\n        methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC,\n                                      wrapperType.getInternalName(),\n                                      boxingMethodName,\n                                      boxingMethodDescriptor,\n                                      false);\n        return size;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/bytebuddy/Variable.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.bytebuddy;\n\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.description.type.TypeDescription.Generic;\nimport net.bytebuddy.implementation.bytecode.StackManipulation;\nimport net.bytebuddy.implementation.bytecode.StackManipulation.Compound;\nimport net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;\n\npublic class Variable {\n    \n    public static Variable of(final Generic variableType, final int offset) {\n        return new Variable(variableType.asErasure(), offset);\n    }\n    private final TypeDescription typeDefinitions;\n    private final int offset;\n    \n    private Variable(final TypeDescription typeDefinitions, final int offset) {\n        this.typeDefinitions = typeDefinitions;\n        this.offset = offset;\n    }\n    \n    public static class VariableAccess {\n    \n        public static StackManipulation load(Variable variable) {return load(variable, false);}\n    \n        public static StackManipulation load(Variable variable, final boolean boxing) {\n            TypeDescription typeDefinitions = variable.typeDefinitions;\n            if (typeDefinitions.isPrimitive() && boxing) {\n                return new Compound(\n                    MethodVariableAccess.of(typeDefinitions).loadFrom(variable.offset),\n                    PrimitiveBoxing.forPrimitive(typeDefinitions)\n                );\n            }else {\n                return MethodVariableAccess.of(typeDefinitions).loadFrom(variable.offset);\n            }\n        }\n        \n        public static StackManipulation store(Variable variable) {\n            return MethodVariableAccess.of(variable.typeDefinitions).storeAt(variable.offset);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/ByteCodeFramework.java",
    "content": "package org.powermock.core.classloader;\n\nimport org.powermock.configuration.GlobalConfiguration;\nimport org.powermock.core.classloader.annotations.PrepareEverythingForTest;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.core.transformers.MockTransformerChainFactory;\nimport org.powermock.core.transformers.javassist.JavassistMockTransformerChainFactory;\n\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Method;\n\npublic enum ByteCodeFramework {\n    Javassist {\n        @Override\n        MockClassLoader createClassloader(final MockClassLoaderConfiguration configuration,\n                                          final UseClassPathAdjuster useClassPathAdjuster) {\n            return new JavassistMockClassLoader(configuration, useClassPathAdjuster);\n        }\n    \n        @Override\n        MockTransformerChainFactory createTransformerChainFactory() {\n            return new JavassistMockTransformerChainFactory();\n        }\n    };\n    \n    public static ByteCodeFramework getByteCodeFrameworkForMethod(final Class<?> testClass, final Method method) {\n        ByteCodeFramework byteCodeFramework = getByteCodeFramework(method);\n        if (byteCodeFramework == null) {\n            byteCodeFramework = getByteCodeFramework(testClass);\n        }\n        if (byteCodeFramework == null) {\n            throw new IllegalArgumentException(\n                String.format(\n                    \"Either method %s or class %s is annotated by PrepareForTest/PrepareEverythingForTest\", method.getName(), testClass.getName()\n                )\n            );\n        }\n        return byteCodeFramework;\n    }\n    \n    public static ByteCodeFramework getByteCodeFrameworkForTestClass(final Class<?> testClass) {\n        ByteCodeFramework byteCodeFramework = getByteCodeFramework(testClass);\n        \n        if (byteCodeFramework == null){\n            byteCodeFramework = GlobalConfiguration.powerMockConfiguration().getByteCodeFramework();\n        }\n        \n        return byteCodeFramework;\n    }\n    \n    private static ByteCodeFramework getByteCodeFramework(final AnnotatedElement element) {\n        if (element.isAnnotationPresent(PrepareForTest.class)) {\n            return element.getAnnotation(PrepareForTest.class).byteCodeFramework();\n        } else if (element.isAnnotationPresent(PrepareOnlyThisForTest.class)) {\n            return element.getAnnotation(PrepareOnlyThisForTest.class).byteCodeFramework();\n        } else if (element.isAnnotationPresent(PrepareEverythingForTest.class)) {\n            return element.getAnnotation(PrepareEverythingForTest.class).byteCodeFramework();\n        } else if (element.isAnnotationPresent(SuppressStaticInitializationFor.class)){\n            return element.getAnnotation(SuppressStaticInitializationFor.class).byteCodeFramework();\n        }\n        return null;\n    }\n    \n    abstract MockClassLoader createClassloader(MockClassLoaderConfiguration configuration, final UseClassPathAdjuster useClassPathAdjuster);\n    \n    abstract MockTransformerChainFactory createTransformerChainFactory();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/ClassMarker.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader;\n\nimport org.powermock.core.transformers.ClassWrapper;\n\n/**\n * Instance of this interface can be used to mark a class that it was created and loaded by PowerMock\n */\npublic interface ClassMarker {\n    /**\n     * Mark type as loaded by PowerMock\n     *\n     * @param type to mark.\n     */\n    <T> void mark(ClassWrapper<T> type);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/ClassloaderWrapper.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader;\n\nimport org.powermock.core.InvocationException;\n\nimport java.util.concurrent.Callable;\n\n// We change the context classloader to the current CL in order for the Mockito\n// framework to load it's plugins (such as MockMaker) correctly.\npublic class ClassloaderWrapper {\n    \n    public static void runWithClass(final Runnable runnable) {\n        runWithClassClassLoader(ClassloaderWrapper.class.getClassLoader(), runnable);\n    }\n    \n    public static void runWithClassClassLoader(final ClassLoader classLoader, final Runnable runnable) {\n        final ClassLoader originalCL = Thread.currentThread().getContextClassLoader();\n        Thread.currentThread().setContextClassLoader(classLoader);\n        try {\n            runnable.run();\n        } finally {\n            Thread.currentThread().setContextClassLoader(originalCL);\n        }\n    }\n    \n    public static <V> V runWithClass(final Callable<V> callable) {\n        return runWithClassClassLoader(ClassloaderWrapper.class.getClassLoader(), callable);\n    }\n    \n    public static <V> V runWithClassClassLoader(final ClassLoader classLoader, final Callable<V> callable) {\n        final ClassLoader originalCL = Thread.currentThread().getContextClassLoader();\n        Thread.currentThread().setContextClassLoader(classLoader);\n        try {\n            return callable.call();\n        } catch (Exception e) {\n            throw new InvocationException(e);\n        } finally {\n            Thread.currentThread().setContextClassLoader(originalCL);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/DeferSupportingClassLoader.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader;\n\nimport org.powermock.reflect.Whitebox;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.ref.SoftReference;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\n/**\n * Defers classloading of system classes to a delegate.\n *\n * @author Johan Haleby\n * @author Jan Kronquist\n * @author Arthur Zagretdinov\n */\nabstract class DeferSupportingClassLoader extends ClassLoader {\n    \n    private final ConcurrentMap<String, SoftReference<Class<?>>> classes;\n    private final ConcurrentMap<String, Object> parallelLockMap;\n    \n    private final MockClassLoaderConfiguration configuration;\n    \n    ClassLoader deferTo;\n    \n    DeferSupportingClassLoader(ClassLoader classloader, MockClassLoaderConfiguration configuration) {\n        \n        this.configuration = configuration;\n        this.classes = new ConcurrentHashMap<String, SoftReference<Class<?>>>();\n        \n        if (classloader == null) {\n            deferTo = ClassLoader.getSystemClassLoader();\n        } else {\n            deferTo = classloader;\n        }\n        parallelLockMap = new ConcurrentHashMap<String,Object>();\n    }\n    \n    @Override\n    public URL getResource(String s) {\n        return deferTo.getResource(s);\n    }\n    \n    @Override\n    public InputStream getResourceAsStream(String s) {\n        return deferTo.getResourceAsStream(s);\n    }\n    \n    @Override\n    public Enumeration<URL> getResources(String name) throws IOException {\n        // If deferTo is already the parent, then we'd end up returning two copies of each resource...\n        if (deferTo.equals(getParent())) {\n            return deferTo.getResources(name);\n        }\n        else {\n            return super.getResources(name);\n        }\n    }\n    \n    public MockClassLoaderConfiguration getConfiguration() {\n        return configuration;\n    }\n    \n    /**\n     * Register a class to the cache of this classloader\n     */\n    public void cache(Class<?> cls) {\n        if (cls != null) {\n            classes.put(cls.getName(), new SoftReference<Class<?>>(cls));\n        }\n    }\n    \n    protected abstract Class<?> loadClassByThisClassLoader(String s) throws ClassFormatError, ClassNotFoundException;\n    \n    @Override\n    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {\n        synchronized (getClassLoadingLock(name)) {\n            Class<?> clazz = findLoadedClass1(name);\n            if (clazz == null) {\n                clazz = loadClass1(name, resolve);\n            }\n            return clazz;\n        }\n    }\n    \n    protected Object getClassLoadingLock(String className) {\n        Object lock = this;\n        if (parallelLockMap != null) {\n            Object newLock = new Object();\n            lock = parallelLockMap.putIfAbsent(className, newLock);\n            if (lock == null) {\n                lock = newLock;\n            }\n        }\n        return lock;\n    }\n    \n    /**\n     * Finds the resource with the specified name on the search path.\n     *\n     * @param name the name of the resource\n     * @return a {@code URL} for the resource, or {@code null} if the\n     * resource could not be found.\n     */\n    @Override\n    protected URL findResource(String name) {\n        try {\n            return Whitebox.invokeMethod(deferTo, \"findResource\", name);\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n    \n    \n    @Override\n    protected Enumeration<URL> findResources(String name) throws IOException {\n        try {\n            return Whitebox.invokeMethod(deferTo, \"findResources\", name);\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n    \n    private Class<?> loadClass1(String name, boolean resolve) throws ClassNotFoundException {\n        Class<?> clazz;\n        if (shouldDefer(name)) {\n            clazz = loadByDeferClassLoader(name);\n        } else {\n            clazz = loadClassByThisClassLoader(name);\n        }\n        if (resolve) {\n            resolveClass(clazz);\n        }\n        classes.put(name, new SoftReference<Class<?>>(clazz));\n        return clazz;\n    }\n    \n    private Class<?> loadByDeferClassLoader(final String name) throws ClassNotFoundException {\n        final Class<?> clazz;\n        clazz = deferTo.loadClass(name);\n        return clazz;\n    }\n    \n    private boolean shouldDefer(String name) {\n        return configuration.shouldDefer(name);\n    }\n    \n    private Class<?> findLoadedClass1(String name) {SoftReference<Class<?>> reference = classes.get(name);\n        Class<?> clazz = null;\n        if (reference != null) {\n            clazz = reference.get();\n        }\n        if (clazz == null) {\n            clazz = findLoadedClass(name);\n        }\n        return clazz;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoader.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.core.classloader;\n\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.ClassWrapperFactory;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.MockTransformerChain;\nimport org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.tests.utils.IgnorePackagesExtractor;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.security.ProtectionDomain;\n\n/**\n * <p>\n * The classloader loads and modified all classes except:\n * </p>\n * <ol>\n * <li>system classes. They are deferred to system classloader</li>\n * <li>classes that locate in packages that specified as packages to ignore with using {@link MockClassLoaderConfiguration#addIgnorePackage(String...)}</li>\n * </ol>\n * <p>\n * Testing frameworks classes are loaded, but not modified.\n * </p>\n * <p>\n * The classloader uses list of {@link MockTransformer} to modify classes during loading.\n * </p>\n *\n * @author Johan Haleby\n * @author Jan Kronquist\n * @author Artur Zagretdinov\n *\n * @see MockClassLoaderConfiguration\n * @see ClassLoader#getSystemClassLoader()\n * @see IgnorePackagesExtractor\n */\npublic abstract class MockClassLoader extends DeferSupportingClassLoader {\n    \n    /**\n     * Pass this string to the constructor to indicate that all classes should\n     * be modified.\n     */\n    public static final String MODIFY_ALL_CLASSES = \"*\";\n    \n    protected ClassMarker classMarker;\n    protected ClassWrapperFactory classWrapperFactory;\n    private MockTransformerChain mockTransformerChain;\n    \n    /**\n     * Creates a new instance of the  based on the\n     * following parameters:\n     *\n     * @param classesToMock   The classes that must be modified to prepare for testability.\n     * @param packagesToDefer Classes in these packages will be defered to the system\n     *                        class-loader.\n     */\n    protected MockClassLoader(String[] classesToMock, String[] packagesToDefer) {\n        this(new MockClassLoaderConfiguration(classesToMock, packagesToDefer), new JavaAssistClassWrapperFactory());\n    }\n    \n    /**\n     * Creates a new instance of the  based on the\n     * following parameters:\n     *\n     * @param configuration The configuration of class loader. Configuration contains information about classes\n     *                      which should be loaded by class loader, defer to system and mocked.\n     * @param classWrapperFactory an instance of {@link ClassWrapperFactory} which is used to wrap internal framework's representation of\n     *                            the class into {@link ClassWrapper}\n     * @see MockClassLoaderConfiguration\n     */\n    protected MockClassLoader(MockClassLoaderConfiguration configuration, final ClassWrapperFactory classWrapperFactory) {\n        super(MockClassLoader.class.getClassLoader(), configuration);\n        this.classWrapperFactory = classWrapperFactory;\n        this.mockTransformerChain = DefaultMockTransformerChain.newBuilder().build();\n    }\n    \n    @Override\n    protected Class<?> loadClassByThisClassLoader(String className) throws ClassFormatError, ClassNotFoundException {\n        final Class<?> loadedClass;\n        Class<?> deferClass = deferTo.loadClass(className);\n        if (getConfiguration().shouldMockClass(className)) {\n            loadedClass = loadMockClass(className, deferClass.getProtectionDomain());\n        } else {\n            loadedClass = loadUnmockedClass(className, deferClass.getProtectionDomain());\n        }\n        return loadedClass;\n    }\n    \n    public void setMockTransformerChain(MockTransformerChain mockTransformerChain) {\n        this.mockTransformerChain = mockTransformerChain;\n    }\n    \n    public MockTransformerChain getMockTransformerChain() {\n        return mockTransformerChain;\n    }\n    \n    protected Class<?> loadUnmockedClass(final String name, final ProtectionDomain protectionDomain) throws ClassNotFoundException {\n        String path = name.replace('.', '/').concat(\".class\");\n        URL res = deferTo.getResource(path);\n        if (res != null) {\n            try {\n                return defineClass(name, res, protectionDomain);\n            } catch (IOException e) {\n                throw new ClassNotFoundException(name, e);\n            }\n        } else {\n            throw new ClassNotFoundException(name);\n        }\n    }\n    \n    private Class<?> defineClass(String name, URL url, final ProtectionDomain protectionDomain) throws IOException {\n        byte[] b = readClass(url);\n        return defineClass(name, b, 0, b.length, protectionDomain);\n    }\n    \n    private byte[] readClass(final URL url) throws IOException {\n        final URLConnection connection = url.openConnection();\n        \n        final InputStream in = connection.getInputStream();\n        ByteArrayOutputStream tmpOut = null;\n        \n        try {\n            \n            final int contentLength = connection.getContentLength();\n            \n            // To avoid having to resize the array over and over and over as\n            // bytes are written to the array, provide an accurate estimate of\n            // the ultimate size of the byte array\n            \n            if (contentLength != -1) {\n                tmpOut = new ByteArrayOutputStream(contentLength);\n            } else {\n                tmpOut = new ByteArrayOutputStream(16384);\n            }\n            \n            byte[] buf = new byte[512];\n            while (true) {\n                int len = in.read(buf);\n                if (len == -1) {\n                    break;\n                }\n                tmpOut.write(buf, 0, len);\n            }\n            return tmpOut.toByteArray();\n        } finally {\n            in.close();\n            if (tmpOut != null) {\n                tmpOut.close();\n            }\n        }\n    }\n    \n    private Class<?> loadMockClass(String name, ProtectionDomain protectionDomain) throws ClassNotFoundException {\n        final byte[] clazz = defineAndTransformClass(name, protectionDomain);\n    \n        return defineClass(name, protectionDomain, clazz);\n    }\n    \n    public Class<?> defineClass(final String name, final ProtectionDomain protectionDomain, final byte[] clazz) {\n        return defineClass(name, clazz, 0, clazz.length, protectionDomain);\n    }\n    \n    protected <T> ClassWrapper<T> transformClass(ClassWrapper<T> wrappedType) throws Exception {\n        wrappedType = mockTransformerChain.transform(wrappedType);\n        \n        if (classMarker != null) {\n            classMarker.mark(wrappedType);\n        }\n        return wrappedType;\n    }\n    \n    protected abstract byte[] defineAndTransformClass(final String name, final ProtectionDomain protectionDomain) throws ClassNotFoundException;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderBuilder.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader;\n\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.MockTransformerChain;\nimport org.powermock.core.transformers.MockTransformerChainFactory;\nimport org.powermock.core.transformers.TestClassAwareTransformer;\nimport org.powermock.utils.ArrayUtil;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.powermock.core.transformers.support.FilterPredicates.isInstanceOf;\nimport static org.powermock.utils.Asserts.internalAssertNotNull;\n\npublic class MockClassLoaderBuilder {\n\n    private final MockTransformerChainFactory transformerChainFactory;\n    private final List<MockTransformer> extraMockTransformers;\n    private final ByteCodeFramework byteCodeFramework;\n    private String[] packagesToIgnore;\n    private String[] classesToModify;\n    \n    public static MockClassLoaderBuilder create(ByteCodeFramework byteCodeFramework) {\n        return new MockClassLoaderBuilder(byteCodeFramework);\n    }\n    \n    private UseClassPathAdjuster useClassPathAdjuster;\n    private Class<?> testClass;\n    \n    private MockClassLoaderBuilder(final ByteCodeFramework byteCodeFramework) {\n        this.byteCodeFramework = byteCodeFramework;\n        transformerChainFactory = byteCodeFramework.createTransformerChainFactory();\n        extraMockTransformers = new ArrayList<MockTransformer>();\n    }\n\n    public MockClassLoader build() {\n        internalAssertNotNull(testClass, \"Test class is null during building classloader. \");\n    \n        final MockClassLoaderConfiguration configuration = new MockClassLoaderConfiguration(classesToModify, packagesToIgnore);\n        final MockClassLoader classLoader = byteCodeFramework.createClassloader(configuration, useClassPathAdjuster);\n    \n        classLoader.setMockTransformerChain(createTransformerChain());\n\n        return classLoader;\n    }\n    \n    private MockTransformerChain createTransformerChain() {\n        final MockTransformerChain mockTransformerChain = transformerChainFactory.createDefaultChain(extraMockTransformers);\n        \n        final Iterable<MockTransformer> testAwareTransformer = mockTransformerChain.filter(isInstanceOf(TestClassAwareTransformer.class));\n        for (MockTransformer transformer : testAwareTransformer) {\n            ((TestClassAwareTransformer) transformer).setTestClass(testClass);\n        }\n        \n        return mockTransformerChain;\n    }\n    \n    public MockClassLoaderBuilder addIgnorePackage(String[] packagesToIgnore) {\n        this.packagesToIgnore = ArrayUtil.addAll(this.packagesToIgnore, packagesToIgnore);\n        return this;\n    }\n\n    public MockClassLoaderBuilder addClassesToModify(String[] classesToModify) {\n        this.classesToModify = ArrayUtil.addAll(this.classesToModify, classesToModify);\n        return this;\n    }\n    \n    public MockClassLoaderBuilder addExtraMockTransformers(MockTransformer... mockTransformers) {\n        if (mockTransformers != null) {\n            for (MockTransformer mockTransformer : mockTransformers) {\n                if (mockTransformer != null) {\n                    extraMockTransformers.add(mockTransformer);\n                }\n            }\n        }\n        return this;\n    }\n    \n    public MockClassLoaderBuilder addClassPathAdjuster(final UseClassPathAdjuster useClassPathAdjuster) {\n        this.useClassPathAdjuster = useClassPathAdjuster;\n        return this;\n    }\n    \n    public MockClassLoaderBuilder forTestClass(final Class<?> testClass) {\n        this.testClass = testClass;\n        return this;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderConfiguration.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader;\n\nimport org.powermock.core.ClassReplicaCreator;\nimport org.powermock.core.WildcardMatcher;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.core.spi.support.InvocationSubstitute;\nimport org.powermock.utils.ArrayUtil;\n\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static org.powermock.core.classloader.MockClassLoader.MODIFY_ALL_CLASSES;\n\n/**\n * The instance of the class provides information about classes which have to be mocked, loaded without modification\n * or defer to system class loader.\n */\npublic class MockClassLoaderConfiguration {\n    \n    /*\n     * Classes that should always be deferred regardless of what the user\n     * specifies in annotations etc.\n     */\n    static final String[] PACKAGES_TO_BE_DEFERRED = new String[]{\n        \"org.hamcrest.*\",\n        \"jdk.*\",\n        \"java.*\",\n        \"javax.accessibility.*\",\n        \"sun.*\",\n        \"org.junit.*\",\n        \"org.testng.*\",\n        \"junit.*\",\n        \"org.pitest.*\",\n        \"org.powermock.modules.junit4.common.internal.*\",\n        \"org.powermock.modules.junit3.internal.PowerMockJUnit3RunnerDelegate*\",\n        \"org.powermock.core*\",\n        \"org.jacoco.agent.rt.*\"\n    };\n    \n    /*\n     * Classes not deferred but loaded by the mock class loader but they're not\n     * modified.\n     */\n    private static final String[] PACKAGES_TO_LOAD_BUT_NOT_MODIFY = new String[]{\n        \"org.junit.\",\n        \"junit.\",\n        \"org.testng.\",\n        \"org.easymock.\",\n        \"net.sf.cglib.\",\n        \"javassist.\",\n        \"org.powermock.modules.junit4.internal.\",\n        \"org.powermock.modules.junit4.legacy.internal.\",\n        \"org.powermock.modules.junit3.internal.\",\n        \"org.powermock\"};\n    \n    private final String[] specificClassesToLoadButNotModify = new String[]{\n        InvocationSubstitute.class.getName(),\n        PowerMockPolicy.class.getName(),\n        ClassReplicaCreator.class.getName()\n    };\n    \n    private final Set<String> modify = Collections.synchronizedSet(new HashSet<String>());\n    private String[] deferPackages;\n    \n    /**\n     * Create an instance of configuration without any classes to mock or ignore.\n     */\n    public MockClassLoaderConfiguration() {\n        this(new String[0], new String[0]);\n    }\n    \n    /**\n     * Create an instance of configuration\n     * @param classesToMock classes that should be modified by {@link MockClassLoader}.\n     * @param packagesToDefer classes/packages that should be deferred to system class loader.\n     */\n    public MockClassLoaderConfiguration(String[] classesToMock, String[] packagesToDefer) {\n        deferPackages = getPackagesToDefer(packagesToDefer);\n        addClassesToModify(classesToMock);\n    }\n    \n    /**\n     * Add packages or classes to ignore. Loading of all classes that locate in the added packages will be delegate to a system classloader.\n     * <p>\n     * Package should be specified with using mask. Example:\n     * </p>\n     * <pre>\n     *     configuration.addIgnorePackage(\"org.powermock.example.*\");\n     * </pre>\n     *\n     * @param packagesToIgnore fully qualified names of classes or names of packages that end by <code>.*</code>\n     */\n    public void addIgnorePackage(String... packagesToIgnore) {\n        if (packagesToIgnore != null && packagesToIgnore.length > 0) {\n            final int previousLength = deferPackages.length;\n            String[] newDeferPackages = new String[previousLength + packagesToIgnore.length];\n            System.arraycopy(deferPackages, 0, newDeferPackages, 0, previousLength);\n            System.arraycopy(packagesToIgnore, 0, newDeferPackages, previousLength, packagesToIgnore.length);\n            deferPackages = newDeferPackages;\n        }\n    }\n    \n    /**\n     * Add classes that will be loaded by the mock classloader, i.e. these\n     * classes will be byte-code manipulated to allow for testing. Any classes\n     * contained in the {@link #PACKAGES_TO_BE_DEFERRED} will be ignored. How ever\n     * classes added here have precedence over additionally deferred (ignored)\n     * packages (those ignored by the user using @PrepareForTest).\n     *\n     * @param classes The fully qualified name of the classes that will be appended\n     *                to the list of classes that will be byte-code modified to\n     *                enable testability.\n     */\n    public final void addClassesToModify(String... classes) {\n        if (classes != null) {\n            for (String clazz : classes) {\n                if (!shouldDefer(PACKAGES_TO_BE_DEFERRED, clazz)) {\n                    modify.add(clazz);\n                }\n            }\n        }\n    }\n    \n    boolean shouldDefer(String className) {\n        return shouldDefer(deferPackages, className);\n    }\n    \n    boolean shouldMockClass(String className) {\n        return shouldModify(className) && !shouldLoadWithMockClassloaderWithoutModifications(className);\n    }\n    \n    String[] getDeferPackages() {\n        return ArrayUtil.clone(deferPackages);\n    }\n    \n    private boolean shouldDefer(String[] packages, String name) {\n        for (String packageToCheck : packages) {\n            if (deferConditionMatches(name, packageToCheck)) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    private boolean deferConditionMatches(String name, String packageName) {\n        final boolean wildcardMatch = WildcardMatcher.matches(name, packageName);\n        return wildcardMatch && !(shouldLoadUnmodifiedClass(name) || shouldModifyClass(name));\n    }\n    \n    private boolean shouldIgnore(String[] packages, String name) {\n        for (String ignore : packages) {\n            if (WildcardMatcher.matches(name, ignore)) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    private boolean shouldLoadUnmodifiedClass(String className) {\n        for (String classNameToLoadButNotModify : specificClassesToLoadButNotModify) {\n            if (className.equals(classNameToLoadButNotModify)) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    private boolean shouldLoadWithMockClassloaderWithoutModifications(String className) {\n        if (className.startsWith(\"org.powermock.example\")) {\n            return false;\n        }\n        for (String packageToLoadButNotModify : PACKAGES_TO_LOAD_BUT_NOT_MODIFY) {\n            if (className.startsWith(packageToLoadButNotModify)) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    private boolean shouldModifyClass(String className) {\n        return modify.contains(className);\n    }\n    \n    private boolean shouldIgnore(String className) {\n        return shouldIgnore(deferPackages, className);\n    }\n    \n    boolean shouldModify(String className) {\n        final boolean shouldIgnoreClass = shouldIgnore(className);\n        final boolean shouldModifyAll = shouldModifyAll();\n        if (shouldModifyAll) {\n            return !shouldIgnoreClass;\n        } else {\n            /*\n             * Never mind if we should ignore the class here since\n             * classes added by prepared for test should (i.e. those added in \"modify\")\n             * have precedence over ignored packages.\n             */\n            return WildcardMatcher.matchesAny(modify, className);\n        }\n    }\n    \n    private boolean shouldModifyAll() {\n        return (modify.size() == 1 && modify.iterator().next().equals(MODIFY_ALL_CLASSES));\n    }\n    \n    private static String[] getPackagesToDefer(final String[] additionalDeferPackages) {\n        final int additionalIgnorePackagesLength = additionalDeferPackages == null ? 0 : additionalDeferPackages.length;\n        final int defaultDeferPackagesLength = PACKAGES_TO_BE_DEFERRED.length;\n        final int allIgnoreLength = defaultDeferPackagesLength + additionalIgnorePackagesLength;\n        final String[] allPackagesToBeIgnored = new String[allIgnoreLength];\n        if (allIgnoreLength > defaultDeferPackagesLength) {\n            System.arraycopy(PACKAGES_TO_BE_DEFERRED, 0, allPackagesToBeIgnored, 0, defaultDeferPackagesLength);\n            System.arraycopy(additionalDeferPackages != null ? additionalDeferPackages : new String[0], 0, allPackagesToBeIgnored, defaultDeferPackagesLength,\n                             additionalIgnorePackagesLength);\n            return allPackagesToBeIgnored;\n        }\n        return PACKAGES_TO_BE_DEFERRED;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader;\n\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.classloader.annotations.PrepareEverythingForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.tests.utils.ArrayMerger;\nimport org.powermock.tests.utils.TestClassesExtractor;\nimport org.powermock.tests.utils.impl.ArrayMergerImpl;\nimport org.powermock.tests.utils.impl.MockPolicyInitializerImpl;\nimport org.powermock.tests.utils.impl.PowerMockIgnorePackagesExtractorImpl;\nimport org.powermock.tests.utils.impl.PrepareForTestExtractorImpl;\nimport org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl;\n\nimport java.lang.reflect.Method;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MockClassLoaderFactory {\n    \n    private final String[] packagesToIgnore;\n    private final Class<?> testClass;\n    private final TestClassesExtractor prepareForTestExtractor;\n    private final TestClassesExtractor suppressionExtractor;\n    private final ArrayMerger arrayMerger;\n    \n    \n    public MockClassLoaderFactory(Class<?> testClass) {\n        this(testClass, new PowerMockIgnorePackagesExtractorImpl().getPackagesToIgnore(testClass));\n    }\n    \n    public MockClassLoaderFactory(Class<?> testClass, String[] packagesToIgnore) {\n        this.testClass = testClass;\n        this.prepareForTestExtractor = new PrepareForTestExtractorImpl();\n        this.suppressionExtractor = new StaticConstructorSuppressExtractorImpl();\n        this.packagesToIgnore = packagesToIgnore;\n        arrayMerger = new ArrayMergerImpl();\n    }\n    \n    public ClassLoader createForClass(final MockTransformer... extraMockTransformer) {\n        final ByteCodeFramework byteCodeFramework = ByteCodeFramework.getByteCodeFrameworkForTestClass(testClass);\n        if (testClass.isAnnotationPresent(PrepareEverythingForTest.class)) {\n            return create(byteCodeFramework, new String[]{MockClassLoader.MODIFY_ALL_CLASSES}, extraMockTransformer);\n        } else {\n            final String[] prepareForTestClasses = prepareForTestExtractor.getTestClasses(testClass);\n            final String[] suppressStaticClasses = suppressionExtractor.getTestClasses(testClass);\n            return create(byteCodeFramework, arrayMerger.mergeArrays(String.class, prepareForTestClasses, suppressStaticClasses), extraMockTransformer);\n        }\n    }\n    \n    public ClassLoader createForMethod(final Method method, final MockTransformer... extraMockTransformers) {\n        final ByteCodeFramework byteCodeFramework = ByteCodeFramework.getByteCodeFrameworkForMethod(testClass, method);\n        if (method.isAnnotationPresent(PrepareEverythingForTest.class)) {\n            final String[] classesToLoadByMockClassloader = {MockClassLoader.MODIFY_ALL_CLASSES};\n            return create(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformers);\n        } else {\n            final String[] suppressStaticClasses = getStaticSuppressionClasses(method);\n            final String[] prepareForTestClasses = prepareForTestExtractor.getTestClasses(method);\n            final String[] classesToLoadByMockClassloader = arrayMerger.mergeArrays(String.class, prepareForTestClasses, suppressStaticClasses);\n            return create(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformers);\n        }\n    }\n    \n    private ClassLoader create(final ByteCodeFramework byteCodeFramework, final String[] prepareForTestClasses,\n                               final MockTransformer... extraMockTransformer) {\n        final String[] classesToLoadByMockClassloader = makeSureArrayContainsTestClassName(prepareForTestClasses, testClass.getName());\n        \n        final ClassLoader mockLoader;\n        if (isContextClassLoaderShouldBeUsed(classesToLoadByMockClassloader)) {\n            mockLoader = Thread.currentThread().getContextClassLoader();\n        } else {\n            mockLoader = createMockClassLoader(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformer);\n        }\n        return mockLoader;\n    }\n    \n    private String[] getStaticSuppressionClasses(Method method) {\n        final String[] testClasses;\n        if (method.isAnnotationPresent(SuppressStaticInitializationFor.class)) {\n            testClasses = suppressionExtractor.getTestClasses(method);\n        } else {\n            testClasses = suppressionExtractor.getTestClasses(testClass);\n        }\n        return testClasses;\n    }\n    \n    private ClassLoader createMockClassLoader(final ByteCodeFramework byteCodeFramework,\n                                              final String[] classesToLoadByMockClassloader,\n                                              final MockTransformer... extraMockTransformer) {\n        \n        final ClassLoader mockLoader = createWithPrivilegeAccessController(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformer);\n    \n        initialize(mockLoader);\n        \n        return mockLoader;\n    }\n    \n    private ClassLoader createWithPrivilegeAccessController(final ByteCodeFramework byteCodeFramework,\n                                                            final String[] classesToLoadByMockClassloader,\n                                                            final MockTransformer... extraMockTransformer) {\n        return AccessController.doPrivileged(new PrivilegedAction<MockClassLoader>() {\n                @Override\n                public MockClassLoader run() {\n                    final UseClassPathAdjuster useClassPathAdjuster = testClass.getAnnotation(UseClassPathAdjuster.class);\n                    return MockClassLoaderFactory.this.createMockClassLoader(byteCodeFramework, classesToLoadByMockClassloader, useClassPathAdjuster, extraMockTransformer);\n                }\n            });\n    }\n    \n    private MockClassLoader createMockClassLoader(final ByteCodeFramework byteCodeFramework,\n                                                  final String[] classesToLoadByMockClassloader,\n                                                  final UseClassPathAdjuster useClassPathAdjuster,\n                                                  final MockTransformer... extraMockTransformer) {\n        return MockClassLoaderBuilder.create(byteCodeFramework)\n                                     .forTestClass(testClass)\n                                     .addIgnorePackage(packagesToIgnore)\n                                     .addClassesToModify(classesToLoadByMockClassloader)\n                                     .addClassPathAdjuster(useClassPathAdjuster)\n                                     .addExtraMockTransformers(extraMockTransformer)\n                                     .build();\n    }\n    \n    private void initialize(final ClassLoader mockLoader) {\n        new MockPolicyInitializerImpl(testClass).initialize(mockLoader);\n    }\n    \n    private boolean isContextClassLoaderShouldBeUsed(String[] classesToLoadByMockClassloader) {\n        return (classesToLoadByMockClassloader == null || classesToLoadByMockClassloader.length == 0) && !hasMockPolicyProvidedClasses(testClass);\n    }\n\n    private String[] makeSureArrayContainsTestClassName(String[] arrayOfClassNames, String testClassName) {\n        if (null == arrayOfClassNames || 0 == arrayOfClassNames.length) {\n            return new String[]{testClassName};\n\n        } else {\n            List<String> modifiedArrayOfClassNames = new ArrayList<String>(arrayOfClassNames.length + 1);\n            modifiedArrayOfClassNames.add(testClassName);\n            for (String className : arrayOfClassNames) {\n                if (testClassName.equals(className)) {\n                    return arrayOfClassNames;\n                } else {\n                    modifiedArrayOfClassNames.add(className);\n                }\n            }\n            return modifiedArrayOfClassNames.toArray(\n                    new String[arrayOfClassNames.length + 1]);\n        }\n    }\n\n    /**\n     * @return {@code true} if there are some mock policies that\n     * contributes with classes that should be loaded by the mock\n     * classloader, {@code false} otherwise.\n     */\n    private boolean hasMockPolicyProvidedClasses(Class<?> testClass) {\n        boolean hasMockPolicyProvidedClasses = false;\n        if (testClass.isAnnotationPresent(MockPolicy.class)) {\n            MockPolicy annotation = testClass.getAnnotation(MockPolicy.class);\n            Class<? extends PowerMockPolicy>[] value = annotation.value();\n            hasMockPolicyProvidedClasses = new MockPolicyInitializerImpl(value).needsInitialization();\n        }\n        return hasMockPolicyProvidedClasses;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/PowerMockModified.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader;\n\n/**\n * Interface marker. If an interface extends the PowerMockModified  or a class implements\n * PowerMockModified  this means that the interface/class has been modified by PowerMock.\n */\npublic interface PowerMockModified {\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/MockPolicy.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader.annotations;\n\nimport org.powermock.core.spi.PowerMockPolicy;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * A Mock Policy can be used to make it easier to unit test some code with\n * PowerMock in isolation from a certain framework. A mock policy implementation\n * can for example suppress some methods, suppress static initializers or\n * intercept method calls and change their return value (for example to return a\n * mock object) for a certain framework or set of classes or interfaces.\n * <p>\n * A mock policy can for example be implemented to avoid writing repetitive\n * setup code for your tests. Say that you're using a framework X that in order\n * for you to test it requires that certain methods should always return a mock\n * implementation. Perhaps some static initializers must be suppressed as well.\n * Instead of copying this code between tests it would be a good idea to write a\n * reusable mock policy.\n */\n@Target( { ElementType.TYPE })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface MockPolicy {\n\t/**\n\t * @return A list of mock policies that should be used in the test class.\n\t */\n\tClass<? extends PowerMockPolicy>[] value();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/PowerMockIgnore.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader.annotations;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * <p>\n * This annotation tells PowerMock to defer the loading of classes with the\n * names supplied to {@link #value()} to the system classloader.\n * </p>\n * <p>\n * For example suppose you'd like to defer the loading of all classes in the\n * <tt>org.myproject</tt> package and all its sub-packages but you still like to\n * prepare \"MyClass\" for test. Then you do like this:\n * </p>\n * <pre>\n * &#064;PowerMockIgnore(&quot;org.myproject.*&quot;)\n * &#064;PrepareForTest(MyClass.class)\n * &#064;RunWith(PowerMockRunner.class)\n * public class MyTest {\n * ...\n * }\n *\n * </pre>\n * <p>\n * This is useful in situations when you have e.g. a test/assertion utility\n * framework (such as something similar to Hamcrest) whose classes must be\n * loaded by the same classloader as EasyMock, JUnit and PowerMock etc.\n * </p>\n * <p>\n * Note that the {@link PrepareForTest} and {@link PrepareOnlyThisForTest} will\n * have precedence over this annotation. This annotation will have precedence\n * over the {@link PrepareEverythingForTest} annotation.\n * </p>\n * <p>\n * Since PowerMock 1.7.0 list of packages/classes which should be loaded by the\n * system classloader can be specified with using {@link org.powermock.configuration.PowerMockConfiguration}.\n * If you want that the test annotated by {@link PowerMockIgnore} then set {@link PowerMockIgnore#globalIgnore()} to <code>false</code>.\n * </p>\n *\n * @see ClassLoader#getSystemClassLoader()\n * @see org.powermock.configuration.PowerMockConfiguration\n */\n@Target({ElementType.TYPE, ElementType.METHOD})\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface PowerMockIgnore {\n    \n    String[] value() default \"\";\n    \n    /**\n     * Set to <code>true</code> if packages from configuration should merge with list of packages/classes from {@link #value()}.\n     * Default value: <code>true</code>\n     *\n     * @return <code>true</code> if packages from configuration should merge with list of packages/classes from {@link #value()}\n     * @since 1.7.0\n     */\n    boolean globalIgnore() default true;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/PowerMockListener.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.classloader.annotations;\n\nimport org.powermock.core.spi.PowerMockTestListener;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * The PowerMock listener annotation can be used to tell PowerMock which\n * listeners should be instantiated and invoked during a test. A listener is\n * invoked according to the events specified in the\n * {@link PowerMockTestListener} interface.\n */\n@Target( { ElementType.TYPE })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface PowerMockListener {\n\tClass<? extends PowerMockTestListener>[] value();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/PrepareEverythingForTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader.annotations;\n\nimport org.powermock.core.classloader.ByteCodeFramework;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * This annotation tells PowerMock to prepare all classes (except certain system\n * and test related classes) for test. Note that static initializers are\n * <i>not</i> removed.\n * <p>\n * The annotation should always be combined with the\n * {@code &#064;RunWith(PowerMockRunner.class)} if using junit 4.x or\n * \n * <pre>\n * public static TestSuite suite() throws Exception {\n * \treturn new PowerMockSuite(MyTestCase.class);\n * }\n * </pre>\n * \n * if using junit3.\n */\n@Target( { ElementType.TYPE, ElementType.METHOD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface PrepareEverythingForTest {\n    ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/PrepareForTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader.annotations;\n\nimport org.powermock.core.IndicateReloadClass;\nimport org.powermock.core.classloader.ByteCodeFramework;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * This annotation tells PowerMock to prepare certain classes for testing.\n * Classes needed to be defined using this annotation are typically those that\n * needs to be byte-code manipulated. This includes final classes, classes with\n * final, private, static or native methods that should be mocked and also\n * classes that should be return a mock object upon instantiation.\n * <p>\n * This annotation can be placed at both test classes and individual test\n * methods. If placed on a class all test methods in this test class will be\n * handled by PowerMock (to allow for testability). To override this behavior\n * for a single method just place a {@code &#064;PrepareForTest} annotation\n * on the specific test method. This is useful in situations where for example\n * you'd like to modify class X in test method A but in test method B you want X\n * to be left intact. In situations like this you place a\n * {@code &#064;PrepareForTest} on method B and exclude class X from the\n * {@link #value()} list.\n * <p>\n * Sometimes you need to prepare inner classes for testing, this can be done by\n * suppling the fully-qualified name of the inner-class that should be mocked to\n * the {@link #fullyQualifiedNames()} list.\n * <p>\n * You can also prepare whole packages for test by using wildcards:\n * \n * <pre>\n * &#064;PrepareForTest(fullyQualifiedNames=&quot;com.mypackage.*&quot;)\n * </pre>\n * \n * <p>\n * The annotation should always be combined with the\n * {@code &#064;RunWith(PowerMockRunner.class)} if using junit 4.x or\n * \n * <pre>\n * public static TestSuite suite() throws Exception {\n *     return new PowerMockSuite(MyTestCase.class);\n * }\n * </pre>\n * \n * if using junit3.\n * <p>\n * The difference between this annotation and the {@link PrepareOnlyThisForTest}\n * annotation is that this annotation modifies the specified classes and all its\n * super classes whereas the {@link PrepareOnlyThisForTest} annotation\n * manipulates <i>only</i> the specified classes.\n */\n@Target( { ElementType.TYPE, ElementType.METHOD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface PrepareForTest {\n    Class<?>[] value() default IndicateReloadClass.class;\n\n    String[] fullyQualifiedNames() default \"\";\n    \n    ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/PrepareOnlyThisForTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader.annotations;\n\nimport org.powermock.core.IndicateReloadClass;\nimport org.powermock.core.classloader.ByteCodeFramework;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * This annotation tells PowerMock to prepare certain classes for testing.\n * Classes needed to be defined using this annotation are typically those that\n * needs to be byte-code manipulated. This includes final classes, classes with\n * final, private, static or native methods that should be mocked and also\n * classes that should be return a mock object upon instantiation.\n * <p>\n * This annotation can be placed at both test classes and individual test\n * methods. If placed on a class all test methods in this test class will be\n * handled by PowerMock (to allow for testability). To override this behavior\n * for a single method just place a {@code &#064;PrepareForTest} annotation\n * on the specific test method. This is useful in situations where for example\n * you'd like to modify class X in test method A but in test method B you want X\n * to be left intact. In situations like this you place a\n * {@code &#064;PrepareForTest} on method B and exclude class X from the\n * {@link #value()} list.\n * <p>\n * Sometimes you need to prepare inner classes for testing, this can be done by\n * suppling the fully-qualified name of the inner-class that should be mocked to\n * the {@link #fullyQualifiedNames()} list.\n * \n * <p>\n * The annotation should always be combined with the\n * {@code &#064;RunWith(PowerMockRunner.class)} if using junit 4.x or\n * \n * <pre>\n * public static TestSuite suite() throws Exception {\n * \treturn new PowerMockSuite(MyTestCase.class);\n * }\n * </pre>\n * \n * if using junit3.\n * <p>\n * The difference between this annotation and the {@link PrepareForTest}\n * annotation is that this annotation only modifies the specified classes\n * whereas the {@link PrepareForTest} annotation manipulates the full class\n * hierarchy. This annotation is recommend if you want full control over which\n * classes that are byte-code manipulated.\n */\n@Target( { ElementType.TYPE, ElementType.METHOD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface PrepareOnlyThisForTest {\n\tClass<?>[] value() default IndicateReloadClass.class;\n\n\tString[] fullyQualifiedNames() default \"\";\n    \n    ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/SuppressStaticInitializationFor.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.classloader.annotations;\n\nimport org.powermock.core.classloader.ByteCodeFramework;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * Use this annotation to suppress static initializers (constructors) for one or\n * more classes.\n * <p>\n * The reason why an annotation is needed for this is because we need to know at\n * <strong>load-time</strong> if the static constructor execution for this\n * class should be skipped or not. Unfortunately we cannot pass the class as the\n * value parameter to the annotation (and thus get type-safe values) because\n * then the class would be loaded before PowerMock could have suppressed its\n * constructor.\n */\n@Target( { ElementType.TYPE, ElementType.METHOD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\npublic @interface SuppressStaticInitializationFor {\n\tString[] value() default \"\";\n    \n    ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/annotations/UseClassPathAdjuster.java",
    "content": "/*\n * Copyright 2013 Jonas Berlin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.classloader.annotations;\n\nimport org.powermock.core.classloader.javassist.ClassPathAdjuster;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * Use this annotation to enable adjusting of the class path used by powermock\n * to locate class files.\n * @deprecated Class path adjuster is supported only for Javassist and will be removed in next release.\n */\n@Target( { ElementType.TYPE, ElementType.METHOD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\n@Inherited\n@Deprecated()\npublic @interface UseClassPathAdjuster {\n    Class<? extends ClassPathAdjuster>  value();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPathAdjuster.java",
    "content": "/*\n * Copyright 2013 Jonas Berlin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.classloader.javassist;\n\nimport javassist.ClassPool;\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\n\n/**\n * This interface can be used to adjust the classpath used by powermock to locate\n * class files. Use the @{@link UseClassPathAdjuster} to activate.\n */\npublic interface ClassPathAdjuster {\n    void adjustClassPath(ClassPool classPool);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPoolFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader.javassist;\n\nimport javassist.ClassClassPath;\nimport javassist.ClassPool;\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\n\nclass ClassPoolFactory {\n    private UseClassPathAdjuster useClassPathAdjuster;\n    \n    ClassPoolFactory(UseClassPathAdjuster useClassPathAdjuster) {\n        this.useClassPathAdjuster = useClassPathAdjuster;\n    }\n    \n    ClassPool create() {\n        ClassPool classPool = new ClassPool();\n        classPool.appendClassPath(new ClassClassPath(this.getClass()));\n        \n        if (useClassPathAdjuster != null) {\n            try {\n                Class<? extends ClassPathAdjuster> value = useClassPathAdjuster.value();\n                ClassPathAdjuster classPathAdjuster = value.newInstance();\n                classPathAdjuster.adjustClassPath(classPool);\n            } catch (Exception e) {\n                throw new RuntimeException(\"Error instantiating class path adjuster\", e);\n            }\n        }\n        \n        return classPool;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavaAssistClassMarkerFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader.javassist;\n\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport org.powermock.core.classloader.ClassMarker;\nimport org.powermock.core.classloader.PowerMockModified;\nimport org.powermock.core.transformers.ClassWrapper;\n\nclass JavaAssistClassMarkerFactory {\n    \n    static ClassMarker createClassMarker(ClassPool classPool) {\n        return new InterfaceClassMarker(classPool);\n    }\n    \n    /**\n     * The implementation of the {@link ClassMarker} which use an interface to mark type.\n     *\n     * @see PowerMockModified\n     */\n    private static class InterfaceClassMarker implements ClassMarker {\n        \n        private final ClassPool classPool;\n        \n        InterfaceClassMarker(ClassPool classPool) {\n            this.classPool = classPool;\n        }\n        \n        /**\n         * Mark type as loaded by PowerMock\n         *\n         * @param type to mark.\n         */\n        @Override\n        public <T> void mark(ClassWrapper<T> type) {\n            T unwrapped = type.unwrap();\n            if (unwrapped instanceof CtClass) {\n                mark((CtClass) unwrapped);\n            }\n        }\n        \n        public void mark(CtClass type) {\n            CtClass powerMockInterface = classPool.makeInterface(\"org.powermock.core.classloader.PowerMockModified\");\n            \n            type.addInterface(powerMockInterface);\n            \n            powerMockInterface.detach();\n            \n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavassistMockClassLoader.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader.javassist;\n\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport javassist.NotFoundException;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.classloader.MockClassLoaderConfiguration;\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory;\n\nimport java.security.ProtectionDomain;\n\npublic class JavassistMockClassLoader extends MockClassLoader {\n    \n    public static final String CGLIB_ENHANCER = \"net.sf.cglib.proxy.Enhancer$EnhancerKey$$KeyFactoryByCGLIB$$\";\n    public static final String CGLIB_METHOD_WRAPPER = \"net.sf.cglib.core.MethodWrapper$MethodWrapperKey$$KeyFactoryByCGLIB\";\n    \n    private final ClassPool classPool;\n    \n    public JavassistMockClassLoader(String[] classesToMock) {\n        this(classesToMock, new String[0], null);\n    }\n    \n    public JavassistMockClassLoader(String[] classesToMock, String[] packagesToDefer,\n                                    UseClassPathAdjuster useClassPathAdjuster) {\n        this(new MockClassLoaderConfiguration(classesToMock, packagesToDefer), useClassPathAdjuster);\n    }\n    \n    public JavassistMockClassLoader(MockClassLoaderConfiguration configuration) {\n        this(configuration, null);\n    }\n    \n    public JavassistMockClassLoader(MockClassLoaderConfiguration configuration,\n                                    UseClassPathAdjuster useClassPathAdjuster) {\n        super(configuration, new JavaAssistClassWrapperFactory());\n        classPool = new ClassPoolFactory(useClassPathAdjuster).create();\n        classMarker = JavaAssistClassMarkerFactory.createClassMarker(classPool);\n    }\n    \n    \n    @Override\n    protected Class<?> loadUnmockedClass(String name, ProtectionDomain protectionDomain)\n        throws ClassFormatError, ClassNotFoundException {\n        byte bytes[] = null;\n        try {\n            /*\n             * TODO This if-statement is a VERY ugly hack to avoid the\n             * java.lang.ExceptionInInitializerError caused by\n             * \"javassist.NotFoundException:\n             * net.sf.cglib.proxy.Enhancer$EnhancerKey$$KeyFactoryByCGLIB$$7fb24d72\n             * \". This happens after the\n             * se.jayway.examples.tests.privatefield.\n             * SimplePrivateFieldServiceClassTest#testUseService(..) tests has\n             * been run and all other tests will fail if this class is tried to\n             * be loaded. Atm I have found no solution other than this ugly hack\n             * to make it work. We really need to investigate the real cause of\n             * this behavior.\n             */\n            if (!name.startsWith(CGLIB_ENHANCER) && !name.startsWith(CGLIB_METHOD_WRAPPER)) {\n                final CtClass ctClass = classPool.get(name);\n                if (ctClass.isFrozen()) {\n                    ctClass.defrost();\n                }\n                bytes = ctClass.toBytecode();\n            }\n        } catch (NotFoundException e) {\n            return ClassLoader.getSystemClassLoader().loadClass(name);\n        } catch (Exception e) {\n            throw new RuntimeException(\"Failed to loaded class \" + name, e);\n        }\n        return bytes == null ? null : defineClass(name, bytes, 0, bytes.length, protectionDomain);\n    }\n    \n    protected byte[] defineAndTransformClass(String name, ProtectionDomain protectionDomain) {\n        final byte[] clazz;\n        \n        ClassPool.doPruning = false;\n        try {\n            CtClass type = classPool.get(name);\n            \n            ClassWrapper<CtClass> wrappedType = classWrapperFactory.wrap(type);\n            \n            wrappedType = transformClass(wrappedType);\n            \n            type = wrappedType.unwrap();\n\n            /*\n             * ClassPool may cause huge memory consumption if the number of CtClass\n             * objects becomes amazingly large (this rarely happens since Javassist\n             * tries to reduce memory consumption in various ways). To avoid this\n             * problem, you can explicitly remove an unnecessary CtClass object from\n             * the ClassPool. If you call detach() on a CtClass object, then that\n             * CtClass object is removed from the ClassPool.\n             */\n            type.detach();\n            \n            \n            clazz = type.toBytecode();\n        } catch (Exception e) {\n            throw new IllegalStateException(\"Failed to transform class with name \" + name + \". Reason: \" + e.getMessage(), e);\n        }\n        return clazz;\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/reporter/MockingFrameworkReporter.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.reporter;\n\n/**\n * The instance of the interface is used to replace default mocking frameworks\n * exception message via message specific for PowerMock use-cases.\n */\npublic interface MockingFrameworkReporter {\n\n    /**\n     * Start replacing mocking frameworks exception message\n     */\n    void enable();\n\n    /**\n     * Stop replacing mocking frameworks exception message\n     */\n    void disable();\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/reporter/PowerMockReporter.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.reporter;\n\n/**\n *  The interface is used to provide a user well-defined exception description.\n */\npublic interface PowerMockReporter {\n\n    <T> void classNotPrepared(Class<T> type);\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/reporter/PowerMockReporterFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.reporter;\n\n/**\n *\n */\n@SuppressWarnings(\"unused\")\npublic interface PowerMockReporterFactory {\n\n     PowerMockReporter createPowerMockReporter();\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/DefaultBehavior.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.spi;\n\n/**\n * Interface that provides the replay, verify and reset behavior for mock\n * objects and classes.\n */\npublic interface DefaultBehavior {\n\n\t/**\n\t * Replay the given objects or classes. May throw exception if replay is not\n\t * needed or not supported.\n\t * \n\t * @param mocks\n\t *            The object(s) to replay. May be {@code null}.\n\t * \n\t * @return the result of the replay (may be {@code null}).\n\t */\n\tObject replay(Object... mocks);\n\n\t/**\n\t * Reset the given objects or classes. May throw exception if reset is not\n\t * needed or not supported.\n\t * \n\t * @param mocks\n\t *            The object(s) to replay. May be {@code null}.\n\t * \n\t * @return the result of the replay (may be {@code null}).\n\t */\n\tObject reset(Object... mocks);\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/MethodInvocationControl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\n\n/**\n * The purpose of a method invocation control is to invoke a proxy to simulate a\n * method call. It also has functionality to replay and verify mocks (which may\n * not be needed for certain invocation controls) and to check whether a certain\n * method is mocked or not.\n * \n */\npublic interface MethodInvocationControl extends InvocationHandler, DefaultBehavior {\n\n\t/**\n\t * Determine whether a certain method is mocked by this Invocation Control.\n\t * \n\t * @param method\n\t *            The method that should be checked.\n\t * @return {@code true} if the method is mocked, {@code false}\n\t *         otherwise.\n\t */\n\tboolean isMocked(Method method);\n\n}"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/NewInvocationControl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.spi;\n\nimport org.powermock.core.spi.support.InvocationSubstitute;\n\n/**\n * A new invocation control pairs up a {@link InvocationSubstitute} with the\n * mock object created when invoking\n * {@link InvocationSubstitute#performSubstitutionLogic(Object...)} object.\n * \n */\npublic interface NewInvocationControl<T> extends DefaultBehavior {\n\n    /**\n     * Invoke the constructor invocation control\n     * @param type invocation target type\n     * @param args arguments of constructor invocation\n     * @param sig parameters of a constructor\n     * @return result of invocation\n     */\n    Object invoke(Class<?> type, Object[] args, Class<?>[] sig) throws Exception;\n\n    /**\n     * Expect a call to the new instance substitution logic.\n     * @param arguments constructor arguments\n     * @return result of stubbing a constructor. Result depends on mocking framework.\n     */\n    T expectSubstitutionLogic(Object... arguments) throws Exception;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/PowerMockPolicy.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi;\n\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\n\n/**\n * This interface can be implemented to create policies for certain frameworks\n * to make it easier for users to test their code in isolation from these\n * frameworks. A mock policy implementation can for example suppress some\n * methods, suppress static initializers or intercept method calls and change\n * their return value (for example to return a mock object). <i>A mock policy\n * implementation must be stateless</i>. The reason why there are two methods\n * for applying settings is that PowerMock needs to know which classes that\n * should be modified by the mock class loader <i>before</i> these classes have\n * loaded. The {@link #applyClassLoadingPolicy(MockPolicyClassLoadingSettings)}\n * tells PowerMock which classes that should be loaded and then the\n * {@link #applyInterceptionPolicy(MockPolicyInterceptionSettings)} is called\n * from the mock class-loader itself. This means you can create mocks for e.g.\n * final and static methods in the\n * {@link #applyInterceptionPolicy(MockPolicyInterceptionSettings)} which would\n * not have been possible otherwise.\n * <p>\n * Since mock policies can be chained subsequent policies can override behavior\n * of a previous policy. To avoid accidental overrides it's recommended\n * <i>add</i> behavior instead of <i>setting</i> behavior since the latter\n * overrides all previous configurations.\n */\npublic interface PowerMockPolicy {\n\n\t/**\n\t * Apply all class-loading related policies that must be present before the\n\t * interception policies can take place.\n\t * \n\t * @param settings\n\t *            The settings objects where the class-loading policies can be\n\t *            applied.\n\t */\n\tvoid applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings);\n\n\t/**\n\t * Apply the interception policies, for example which methods that should be\n\t * suppressed or which methods that should be intercepted and return some\n\t * else than their original value.\n\t * \n\t * @param settings\n\t *            The settings objects where the interception policies can be\n\t *            applied.\n\t */\n\tvoid applyInterceptionPolicy(MockPolicyInterceptionSettings settings);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/PowerMockTestListener.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi;\n\nimport org.powermock.core.spi.testresult.TestMethodResult;\nimport org.powermock.core.spi.testresult.TestSuiteResult;\n\nimport java.lang.reflect.Method;\n\n/**\n * This interface should be implemented by all PowerMock test listeners. The\n * listener will be notified on the events present in this interface. Please\n * note that a listener cannot hold state.\n */\npublic interface PowerMockTestListener {\n\n\t/**\n\t * Invoked once before the test run has started.\n\t * \n\t * @param testClass\n\t *            The type of the test to be executed.\n\t * @param testMethods\n\t *            The test methods that will be executed during the test.\n\t * @throws Exception\n\t *             If something unexpected occurs.\n\t */\n\tvoid beforeTestSuiteStarted(Class<?> testClass, Method[] testMethods) throws Exception;\n\n\t/**\n\t * Invoked before each test method.\n\t * \n\t * @param testInstance\n\t *            The test case instance.\n\t * @param method\n\t *            The test method that is currently executed.\n\t * @param arguments\n\t *            The arguments passed to the test method if any. May be an\n\t *            empty array but never {@code null}.\n\t * @throws Exception\n\t *             If something unexpected occurs.\n\t */\n\tvoid beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception;\n\n\t/**\n\t * Invoked after each test method.\n\t * \n\t * * @param testInstance The test case instance.\n\t * \n\t * @param method\n\t *            The test method that is currently executed.\n\t * @param arguments\n\t *            The arguments passed to the test method if any. May be an\n\t *            empty array but never {@code null}.\n\t * @param testResult\n\t *            The outcome of the test method.\n\t * @throws Exception\n\t *             If something unexpected occurs.\n\t */\n\tvoid afterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) throws Exception;\n\n\t/**\n\t * Invoked after a test suite has ended.\n\t * \n\t * @param testClass\n\t *            The type of the test to be executed.\n\t * @param methods\n\t *            The test methods that were executed during the test.\n\t * @param testResult\n\t *            The outcome of the test suite.\n\t * @throws Exception\n\t *             If something unexpected occurs.\n\t */\n\tvoid afterTestSuiteEnded(Class<?> testClass, Method[] methods, TestSuiteResult testResult) throws Exception;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/listener/AnnotationEnablerListener.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.listener;\n\nimport org.powermock.core.spi.PowerMockTestListener;\n\nimport java.lang.annotation.Annotation;\n\npublic interface AnnotationEnablerListener extends PowerMockTestListener {\n\n    /**\n     * @return The mock annotations considered by this annotation enabler.\n     */\n    Class<? extends Annotation>[] getMockAnnotations();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/support/AbstractPowerMockTestListenerBase.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.support;\n\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.core.spi.testresult.TestMethodResult;\nimport org.powermock.core.spi.testresult.TestSuiteResult;\n\nimport java.lang.reflect.Method;\n\n/**\n * An empty implementation of the {@link PowerMockTestListener} interface. May\n * be inherited by clients that wants to provide empty implementations of some\n * of the interface methods.\n */\npublic class AbstractPowerMockTestListenerBase implements PowerMockTestListener {\n\n\t/**\n\t * Provides an empty implementation.\n\t */\n\t@Override\n\tpublic void afterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) throws Exception {\n\t}\n\n\t/**\n\t * Provides an empty implementation.\n\t */\n\t@Override\n\tpublic void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception {\n\t}\n\n\t/**\n\t * Provides an empty implementation.\n\t */\n\t@Override\n\tpublic void beforeTestSuiteStarted(Class<?> testClass, Method[] testMethods) throws Exception {\n\t}\n\n\t/**\n\t * Provides an empty implementation.\n\t */\n\t@Override\n\tpublic void afterTestSuiteEnded(Class<?> testClass, Method[] methods, TestSuiteResult testResult) throws Exception {\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/support/InvocationSubstitute.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.support;\n\n/**\n * A class that can be used as a substitution instead of mocking a particular\n * class. For example when mocking a new instance call you can fake the\n * constructor invocation by creating a mock object (A) for this class and\n * invoke the {@link #performSubstitutionLogic(Object...)} method instead with\n * the constructor arguments. The interception process must take care of doing\n * this. Also remember that behaviors such as replay and/or verify must be\n * performed on (A).\n * \n */\npublic interface InvocationSubstitute<T> {\n    T performSubstitutionLogic(Object... arguments) throws Exception;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/testresult/Result.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.testresult;\n\npublic enum Result {\n\tSUCCESSFUL, FAILED, IGNORED\n}"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/testresult/TestMethodResult.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.testresult;\n\npublic interface TestMethodResult {\n\n\tResult getResult();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/testresult/TestSuiteResult.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.testresult;\n\npublic interface TestSuiteResult {\n\n\tint getTestCount();\n\n\tint getIgnoreCount();\n\t\n\tint getSuccessCount();\n\t\n\tint getFailureCount();\n\n\tResult getResult();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/testresult/impl/TestMethodResultImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.testresult.impl;\n\nimport org.powermock.core.spi.testresult.Result;\nimport org.powermock.core.spi.testresult.TestMethodResult;\n\npublic class TestMethodResultImpl implements TestMethodResult {\n\n\tprivate final Result result;\n\n\tpublic TestMethodResultImpl(Result result) {\n\t\tsuper();\n\t\tthis.result = result;\n\t}\n\n\t@Override\n\tpublic Result getResult() {\n\t\treturn result;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn result.toString();\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/spi/testresult/impl/TestSuiteResultImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.spi.testresult.impl;\n\nimport org.powermock.core.spi.testresult.Result;\nimport org.powermock.core.spi.testresult.TestSuiteResult;\n\npublic class TestSuiteResultImpl implements TestSuiteResult {\n\n\tprivate int failureCount;\n\n\tprivate int successCount;\n\n\tprivate int testCount;\n\n\tprivate int ignoreCount;\n\n\tpublic TestSuiteResultImpl() {\n\t}\n\n\tpublic TestSuiteResultImpl(int failureCount, int successCount, int testCount, int ignoreCount) {\n\t\tthis.failureCount = failureCount;\n\t\tthis.successCount = successCount;\n\t\tthis.testCount = testCount;\n\t\tthis.ignoreCount = ignoreCount;\n\t}\n\n\t@Override\n\tpublic int getFailureCount() {\n\t\treturn failureCount;\n\t}\n\n\t@Override\n\tpublic int getSuccessCount() {\n\t\treturn successCount;\n\t}\n\n\t@Override\n\tpublic int getIgnoreCount() {\n\t\treturn ignoreCount;\n\t}\n\n\t@Override\n\tpublic Result getResult() {\n\t\tResult result = Result.SUCCESSFUL;\n\t\tif (testCount == 0) {\n\t\t\tresult = Result.IGNORED;\n\t\t} else if (failureCount != 0) {\n\t\t\tresult = Result.FAILED;\n\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic int getTestCount() {\n\t\treturn testCount;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn getResult().toString();\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/testlisteners/FieldDefaulter.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.testlisteners;\n\nimport org.powermock.core.spi.support.AbstractPowerMockTestListenerBase;\nimport org.powermock.core.spi.testresult.TestMethodResult;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.internal.TypeUtils;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\n/**\n * A test listener that automatically set all instance fields to their default\n * values after each test method. E.g. an object field is set to\n * {@code null}, an {@code int} field is set to 0 and so on.\n */\npublic class FieldDefaulter extends AbstractPowerMockTestListenerBase {\n\n\t@Override\n\tpublic void afterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) throws Exception {\n\t\tSet<Field> allFields = Whitebox.getAllInstanceFields(testInstance);\n\t\tfor (Field field : allFields) {\n\t\t\tfield.set(testInstance, TypeUtils.getDefaultValue(field.getType()));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupport.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.testlisteners;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * Core static utility to help modules, such as PowerMockRunner, that needs to\n * communicate with some 3rd-party framework in order to properly fire\n * events to PowerMockTestListener instances.\n */\npublic class GlobalNotificationBuildSupport {\n\n    public interface Callback {\n        void suiteClassInitiated(Class<?> testClass);\n\n        void testInstanceCreated(Object testInstance);\n    }\n\n    private static final Map<String, Callback> testSuiteCallbacks =\n            new ConcurrentHashMap<String, Callback>();\n\n    private static final Map<Class<?>, Callback> initiatedTestSuiteClasses =\n            new ConcurrentHashMap<Class<?>, Callback>();\n\n    private static final ThreadLocal<Class<?>> pendingInitiatedTestClass =\n            new ThreadLocal<Class<?>>();\n\n    public static void prepareTestSuite(\n            String testClassName, Callback callback) {\n        if (testSuiteCallbacks.containsKey(testClassName)) {\n            throw new IllegalStateException(\n                    \"Needs to wait for concurrent test-suite execution to start!\");\n        } else {\n            testSuiteCallbacks.put(testClassName, callback);\n            Class<?> initiatedTestClass = pendingInitiatedTestClass.get();\n            if (null != initiatedTestClass\n                    && initiatedTestClass.getName().equals(testClassName)) {\n                System.err.println(\"Detected late test-suite preparation of \"\n                        + \"already initiated test-\" + initiatedTestClass);\n                testClassInitiated(initiatedTestClass);\n            }\n        }\n    }\n\n    public static void testClassInitiated(Class<?> testClass) {\n        if (!initiatedTestSuiteClasses.containsKey(testClass)) {\n            Callback callback = testSuiteCallbacks.get(testClass.getName());\n            if (null == callback) {\n                pendingInitiatedTestClass.set(testClass);\n            } else {\n                initiatedTestSuiteClasses.put(testClass, callback);\n                callback.suiteClassInitiated(testClass);\n                pendingInitiatedTestClass.set(null);\n            }\n        }\n    }\n\n    private static int countInitializersInTrace(final String className) {\n        int initializerCount = 0;\n        for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {\n            if (\"<init>\".equals(ste.getMethodName())\n                    && className.equals(ste.getClassName())\n                    && 2 <= ++initializerCount) {\n                return 2;\n            }\n        }\n        return initializerCount;\n    }\n\n    public static void testInstanceCreated(Object testInstance) {\n        for (Class<?> c = testInstance.getClass(); Object.class != c; c = c.getSuperclass()) {\n            Callback callback = initiatedTestSuiteClasses.get(c);\n            if (null != callback) {\n                if (1 == countInitializersInTrace(c.getName())) {\n                    callback.testInstanceCreated(testInstance);\n                }\n                return;\n            }\n        }\n    }\n\n    public static void closeTestSuite(Class<?> testClass) {\n        Callback callback = initiatedTestSuiteClasses.remove(testClass);\n        if (null != callback\n                && !initiatedTestSuiteClasses.values().contains(callback)) {\n            testSuiteCallbacks.values().remove(callback);\n        }\n    }\n\n    public static void closePendingTestSuites(Callback callback) {\n        testSuiteCallbacks.values().remove(callback);\n        initiatedTestSuiteClasses.values()\n                .removeAll(java.util.Collections.singleton(callback));\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/ClassWrapper.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\n/**\n * An interface represents an abstraction of the class to be able to pass class to different byte-code instrumentation frameworks.\n *\n * @param <T> - original class specific for byte-code modification framework.\n * @author Arthur Zagretdinov\n */\npublic interface ClassWrapper<T> {\n    \n    /**\n     * Check if class is interface\n     *\n     * @return <code>true</code> if class is an interface.\n     */\n    boolean isInterface();\n    \n    /**\n     * Get original object which represent class\n     *\n     * @return instance of original object.\n     */\n    T unwrap();\n    \n    /**\n     * Wrap changed implementation to get a new instance of ClassWrapper\n     * @param original -  original class specific for byte-code modification framework.\n     * @return a new instance of ClassWrapper\n     */\n    ClassWrapper<T> wrap(T original);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/ClassWrapperFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\n/**\n * An implementation should wrap original instance.\n *\n * @param <T> - original class specific for byte-code modification framework.\n * @author Arthur Zagretdinov\n */\npublic interface ClassWrapperFactory<T> {\n    \n    /**\n     * @param original - original class specific for byte-code modification framework.\n     * @return wrapped original class as {@link ClassWrapper}\n     */\n    ClassWrapper<T> wrap(T original);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatureWriter.java",
    "content": "package org.powermock.core.transformers;\n\n\nimport java.lang.reflect.Method;\n\npublic interface MethodSignatureWriter<T> {\n    String signatureFor(T method);\n    \n    String signatureForReflection(Method method);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatures.java",
    "content": "package org.powermock.core.transformers;\n\nimport javassist.CtClass;\nimport javassist.CtMethod;\nimport javassist.NotFoundException;\nimport net.bytebuddy.description.method.MethodDescription;\nimport org.powermock.PowerMockInternalException;\n\nimport java.lang.reflect.Method;\n\npublic enum MethodSignatures {\n    \n    ByteBuddy {\n        @Override\n        public MethodSignatureWriter<MethodDescription> methodSignatureWriter() {\n            return new ByteBuddyMethodSignatureWriterWriter();\n        }\n    },\n    \n    Javassist {\n        @Override\n        public MethodSignatureWriter<CtMethod> methodSignatureWriter() {\n            return new JavassistMethodSignatureWriterWriter();\n        }\n    };\n    \n    public abstract <T> MethodSignatureWriter<T> methodSignatureWriter();\n    \n    private static class ByteBuddyMethodSignatureWriterWriter implements MethodSignatureWriter<MethodDescription> {\n        \n        @Override\n        public String signatureFor(final MethodDescription method) {\n            return method.toGenericString();\n        }\n        \n        @Override\n        public String signatureForReflection(final Method method) {\n            return method.toString();\n        }\n    }\n    \n    private static class JavassistMethodSignatureWriterWriter implements MethodSignatureWriter<CtMethod> {\n        @Override\n        public String signatureFor(final CtMethod m) {\n            try {\n                CtClass[] paramTypes = m.getParameterTypes();\n                String[] paramTypeNames = new String[paramTypes.length];\n                for (int i = 0; i < paramTypeNames.length; ++i) {\n                    paramTypeNames[i] = paramTypes[i].getSimpleName();\n                }\n                return createSignature(\n                    m.getDeclaringClass().getSimpleName(),\n                    m.getReturnType().getSimpleName(),\n                    m.getName(), paramTypeNames);\n            } catch (NotFoundException e) {\n                throw new PowerMockInternalException(e);\n            }\n        }\n        \n        @Override\n        public String signatureForReflection(final Method m) {\n            Class[] paramTypes = m.getParameterTypes();\n            String[] paramTypeNames = new String[paramTypes.length];\n            for (int i = 0; i < paramTypeNames.length; ++i) {\n                paramTypeNames[i] = paramTypes[i].getSimpleName();\n            }\n            return createSignature(\n                m.getDeclaringClass().getSimpleName(),\n                m.getReturnType().getSimpleName(),\n                m.getName(), paramTypeNames);\n        }\n        \n        private String createSignature(\n            String testClass, String returnType, String methodName,\n            String[] paramTypes) {\n            StringBuilder builder = new StringBuilder(testClass)\n                                        .append('\\n').append(returnType)\n                                        .append('\\n').append(methodName);\n            for (String param : paramTypes) {\n                builder.append('\\n').append(param);\n            }\n            return builder.toString();\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/MockTransformer.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.core.transformers;\n\n/**\n * Interface that all mock transformers must implement. The purpose of a mock\n * transformer is to create a modified version of a {@code Class} so that\n * it is mock enabled.\n *\n * @author Johan Haleby\n */\npublic interface MockTransformer<T> {\n    \n    /**\n     * Transforms the {@code clazz}.\n     *\n     * @param clazz The class to be\n     *              transform into a mock enabled class.\n     * @return A {@code ClassWrapper} representation of the mocked class.\n     */\n    ClassWrapper<T> transform(ClassWrapper<T> clazz) throws Exception;\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/MockTransformerChain.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport java.util.Collection;\n\n/**\n * Interface represent chain of {@link MockTransformer}.\n * Each transformer in chain instruments a class to enable one of mocking feature.\n *\n * @author Arthur Zagretdinov\n */\npublic interface MockTransformerChain {\n    \n    /**\n     * Go thought all transformers in chain and instrument the {@code clazz}.\n     *\n     * @param clazz The class to be instrument to enabled class mocking.\n     * @return A {@code ClassWrapper} representation of the instrumented class.\n     */\n    <T> ClassWrapper<T> transform(ClassWrapper<T> clazz) throws Exception;\n    \n    /**\n     * Filter and return collection of {@link MockTransformer} which fit the <code>predicate</code>.\n     * @param predicate to test MockTransformer\n     * @return collection of {@link MockTransformer} which fit the {@link FilterPredicate}\n     */\n    Collection<MockTransformer> filter(FilterPredicate predicate);\n    \n    interface FilterPredicate {\n        boolean test(MockTransformer<?> mockTransformer);\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/MockTransformerChainFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport java.util.List;\n\n/**\n * An implementation of interface should create a {@link MockTransformerChain} with full set of required transformers to enable all mocking features.\n *\n * @author Arthur Zagretdinov\n */\npublic interface MockTransformerChainFactory {\n    \n    /**\n     * Create an {@link MockTransformerChain} with using default strategy {@link TransformStrategy#CLASSLOADER}\n     *\n     * @return an instance of MockTransformerChain\n     */\n    MockTransformerChain createDefaultChain();\n    \n    /**\n     * Create an {@link MockTransformerChain} with using the given <code>transformStrategy</code>\n     *\n     * @return an instance of MockTransformerChain\n     */\n    MockTransformerChain createDefaultChain(TransformStrategy transformStrategy);\n    \n    /**\n     * Create an {@link MockTransformerChain} with using default strategy {@link TransformStrategy#CLASSLOADER} and with the given <code>extraMockTransformers</code>\n     *\n     * @return an instance of MockTransformerChain\n     */\n    MockTransformerChain createDefaultChain(List<MockTransformer> extraMockTransformers);\n    \n    /**\n     * Create an {@link MockTransformerChain} with using the given <code>testClassTransformer</code> as transformer for test class.\n     *\n     * @return an instance of MockTransformerChain\n     */\n    MockTransformerChain createTestClassChain(MockTransformer testClassTransformer);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/TestClassAwareTransformer.java",
    "content": "package org.powermock.core.transformers;\n\n/**\n * If a transformer implements this interface then {@link org.powermock.core.classloader.MockClassLoaderBuilder} sets current test class during building a instance of {@link org.powermock.core.classloader.MockClassLoader}.\n * <b>IMPORTANT</b>\n * This may take affect only with running PowerMock with class loader mode, a <code>testClass</code> will not be set in case if PowerMock used as JavaAgent.\n */\npublic interface TestClassAwareTransformer {\n    void setTestClass(Class<?> testClass);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.powermock.core.transformers.javassist.ConstructorsMockTransformer;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\n/**\n * MockTransformer implementation that will make PowerMock test-class\n * enhancements for four purposes...\n * 1) Make test-class static initializer and constructor send crucial details\n * (for PowerMockTestListener events) to GlobalNotificationBuildSupport so that\n * this information can be forwarded to whichever\n * facility is used for composing the PowerMockTestListener events.\n * 2) Removal of test-method annotations as a mean to achieve test-suite\n * chunking!\n * 3) Restore original test-class constructors` accesses\n * (in case they have all been made public by {@link ConstructorsMockTransformer})\n * - to avoid that multiple <i>public</i> test-class constructors cause\n * a delegate runner from JUnit (or 3rd party) to bail out with an\n * error message such as \"Test class can only have one constructor\".\n * 4) Set test-class defer constructor (if exist) as protected instead of public.\n * Otherwise a delegate runner from JUnit (or 3rd party) might get confused by\n * the presence of more than one test-class constructor and bail out with an\n * error message such as \"Test class can only have one constructor\".\n * <p>\n * The #3 and #4 enhancements will also be enforced on the constructors\n * of classes that are nested within the test-class.\n */\npublic abstract class TestClassTransformer<T, M> implements MockTransformer<T> {\n    \n    private final Class<?> testClass;\n    private final Class<? extends Annotation> testMethodAnnotationType;\n    private final MethodSignatureWriter<M> methodSignatureWriter;\n    \n    public TestClassTransformer(Class<?> testClass, Class<? extends Annotation> testMethodAnnotationType,\n                                MethodSignatureWriter<M> methodSignatureWriter) {\n        this.testClass = testClass;\n        this.testMethodAnnotationType = testMethodAnnotationType;\n        this.methodSignatureWriter = methodSignatureWriter;\n    }\n    \n    protected String signatureOf(final M method) {\n        return methodSignatureWriter.signatureFor(method);\n    }\n    \n    protected String signatureOf(final Method m) {\n        return methodSignatureWriter.signatureForReflection(m);\n    }\n    \n    protected Class<? extends Annotation> getTestMethodAnnotationType() {\n        return testMethodAnnotationType;\n    }\n    \n    protected Class<?> getTestClass() {\n        return testClass;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformerBuilder.java",
    "content": "package org.powermock.core.transformers;\n\nimport javassist.CtMethod;\nimport org.powermock.core.classloader.ByteCodeFramework;\nimport org.powermock.core.transformers.javassist.testclass.ForMethodsJavaAssistTestClassTransformer;\nimport org.powermock.core.transformers.javassist.testclass.FromAllMethodsExceptJavaAssistTestClassTransformer;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\nimport java.util.Collection;\n\npublic class TestClassTransformerBuilder {\n    \n    public static TestClassTransformerBuilder forTestClass(final Class<?> testClass) {\n        return new TestClassTransformerBuilder(testClass);\n    }\n    \n    private final Class<?> testClass;\n    \n    private TestClassTransformerBuilder(final Class<?> testClass) {\n        this.testClass = testClass;\n    }\n    \n    public RemovesTestMethodAnnotation removesTestMethodAnnotation(final Class<? extends Annotation> testMethodAnnotation) {\n        return new RemovesTestMethodAnnotation(testClass, testMethodAnnotation, ByteCodeFramework.getByteCodeFrameworkForTestClass(testClass));\n    }\n    \n    public TestClassTransformerBuilderWithClue bytecodeFrameworkClue(final Method method) {\n        return new TestClassTransformerBuilderWithClue(testClass, method);\n    }\n    \n    public static class TestClassTransformerBuilderWithClue {\n        \n        private final Class<?> testClass;\n        private final Method method;\n        \n        private TestClassTransformerBuilderWithClue(final Class<?> testClass, final Method method) {\n            this.testClass = testClass;\n            this.method = method;\n        }\n        \n        public RemovesTestMethodAnnotation removesTestMethodAnnotation(final Class<? extends Annotation> testMethodAnnotation) {\n            return new RemovesTestMethodAnnotation(testClass, testMethodAnnotation, ByteCodeFramework.getByteCodeFrameworkForMethod(testClass, method));\n        }\n    }\n    \n    public static class RemovesTestMethodAnnotation {\n        private final Class<? extends Annotation> testMethodAnnotation;\n        private final Class<?> testClass;\n        private final ByteCodeFramework byteCodeFramework;\n        \n        private RemovesTestMethodAnnotation(final Class<?> testClass, final Class<? extends Annotation> testMethodAnnotation,\n                                            final ByteCodeFramework byteCodeFramework) {\n            this.testClass = testClass;\n            this.testMethodAnnotation = testMethodAnnotation;\n            this.byteCodeFramework = byteCodeFramework;\n        }\n        \n        public TestClassTransformer fromMethods(final Collection<Method> testMethodsThatRunOnOtherClassLoaders) {\n            switch (byteCodeFramework) {\n                case Javassist:\n                    return new ForMethodsJavaAssistTestClassTransformer(\n                        testClass, testMethodAnnotation, MethodSignatures.Javassist.<CtMethod>methodSignatureWriter(), testMethodsThatRunOnOtherClassLoaders\n                    );\n                default:\n                    throw new IllegalArgumentException(String.format(\"Unknown bytecode framework `%s`\", byteCodeFramework));\n            }\n        }\n        \n        public TestClassTransformer fromAllMethodsExcept(Method singleMethodToRunOnTargetClassLoader) {\n            switch (byteCodeFramework) {\n                case Javassist:\n                    return new FromAllMethodsExceptJavaAssistTestClassTransformer(\n                        testClass, testMethodAnnotation, MethodSignatures.Javassist.<CtMethod>methodSignatureWriter(), singleMethodToRunOnTargetClassLoader\n                    );\n                default:\n                    throw new IllegalArgumentException(String.format(\"Unknown bytecode framework `%s`\", byteCodeFramework));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/TransformStrategy.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.transformers;\n\n/**\n * The enum provide information for {@link MockTransformer} have PowerMock is started via Runner(FactoryObject), Rule or JavaAgent\n */\npublic enum TransformStrategy {\n    CLASSLOADER {\n        @Override\n        public boolean isClassloaderMode() {\n            return true;\n        }\n    \n        @Override\n        public boolean isAgentMode() {\n            return false;\n        }\n    },\n    INST_REDEFINE {\n        @Override\n        public boolean isClassloaderMode() {\n            return false;\n        }\n    \n        @Override\n        public boolean isAgentMode() {\n            return true;\n        }\n    };\n    \n    /**\n     * Check if this strategy is supported by class loader. It means that more byte code instrumenting are allowed: like adding constructor,\n     * changeling method signature and so on\n     * @return <code>true</code> if a strategy is supported by class loader.\n     */\n    public abstract boolean isClassloaderMode();\n    \n    /**\n     * Check if this strategy is supported only by Java Agent. It means that lest byte code instrumenting are allowed and PowerMock should\n     * avoid using some instrument things.\n     * @return <code>true</code> if a strategy is supported only by Java Agent\n     */\n    public abstract boolean isAgentMode();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/AbstractJavaAssistMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CtClass;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.TransformStrategy;\n\npublic abstract class AbstractJavaAssistMockTransformer implements MockTransformer<CtClass> {\n    \n    private final TransformStrategy strategy;\n    \n    public AbstractJavaAssistMockTransformer(TransformStrategy strategy) {\n        this.strategy = strategy;\n    }\n    \n    @Override\n    public ClassWrapper<CtClass> transform(final ClassWrapper<CtClass> clazz) throws Exception {\n        if (clazz.unwrap() instanceof  CtClass) {\n            CtClass classImpl = clazz.unwrap();\n        \n            if (classImpl != null) {\n                transform(classImpl);\n            }\n        }\n    \n        return clazz;\n    }\n    \n    public abstract CtClass transform(CtClass clazz) throws Exception;\n    \n    protected TransformStrategy getStrategy() {\n        return strategy;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/ClassFinalModifierMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CtClass;\nimport javassist.Modifier;\nimport javassist.bytecode.AttributeInfo;\nimport javassist.bytecode.ClassFile;\nimport javassist.bytecode.InnerClassesAttribute;\nimport org.powermock.core.transformers.TransformStrategy;\n\nimport static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE;\n\npublic class ClassFinalModifierMockTransformer extends AbstractJavaAssistMockTransformer {\n    \n    public ClassFinalModifierMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n    }\n    \n    @Override\n    public CtClass transform(final CtClass clazz) {\n        if (clazz.isInterface()) {\n            return clazz;\n        }\n        \n        if (getStrategy() != INST_REDEFINE) {\n            if (Modifier.isFinal(clazz.getModifiers())) {\n                clazz.setModifiers(clazz.getModifiers() ^ Modifier.FINAL);\n            }\n            \n            ClassFile classFile = clazz.getClassFile2();\n            AttributeInfo attribute = classFile.getAttribute(InnerClassesAttribute.tag);\n            if (attribute != null && attribute instanceof InnerClassesAttribute) {\n                InnerClassesAttribute ica = (InnerClassesAttribute) attribute;\n                String name = classFile.getName();\n                int n = ica.tableLength();\n                for (int i = 0; i < n; ++i) {\n                    if (name.equals(ica.innerClass(i))) {\n                        int accessFlags = ica.accessFlags(i);\n                        if (Modifier.isFinal(accessFlags)) {\n                            ica.setAccessFlags(i, accessFlags ^ Modifier.FINAL);\n                        }\n                    }\n                }\n            }\n        }\n        \n        return clazz;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/ConstructorsMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CtClass;\nimport javassist.CtConstructor;\nimport javassist.Modifier;\nimport javassist.NotFoundException;\nimport org.powermock.core.transformers.TransformStrategy;\n\nimport static org.powermock.core.transformers.TransformStrategy.CLASSLOADER;\n\n/**\n * Convert all constructors to public\n */\npublic class ConstructorsMockTransformer extends AbstractJavaAssistMockTransformer {\n    \n    public ConstructorsMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n    }\n    \n    @Override\n    public CtClass transform(final CtClass clazz) {\n        if (clazz.isInterface()) {\n            return clazz;\n        }\n        \n        if (getStrategy() == CLASSLOADER) {\n            transform(new CtClass[]{clazz});\n            // we also need to transform nested class at this time due to JEP181 since JDK11\n            // otherwise, we might have trouble during further transformation\n            // see github #958\n            try {\n                CtClass[] nestedClasses = clazz.getDeclaredClasses();\n                transform(nestedClasses);\n            } catch (NotFoundException ignored) {\n                // ignored\n            }\n        }\n        return clazz;\n    }\n\n    private static void transform(final CtClass[] clazzArray) {\n        for (CtClass nestedClazz : clazzArray) {\n            for (CtConstructor c : nestedClazz.getDeclaredConstructors()) {\n                final int modifiers = c.getModifiers();\n                if (!Modifier.isPublic(modifiers)) {\n                    c.setModifiers(Modifier.setPublic(modifiers));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/InstrumentMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CannotCompileException;\nimport javassist.CtClass;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.transformers.TransformStrategy;\nimport org.powermock.core.transformers.javassist.support.PowerMockExpressionEditor;\n\nimport java.io.File;\nimport java.io.OutputStream;\n\npublic class InstrumentMockTransformer extends AbstractJavaAssistMockTransformer {\n    \n    private Class<?> mockGetawayClass;\n    \n    public InstrumentMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n        this.mockGetawayClass = MockGateway.class;\n    }\n    \n    @Override\n    public CtClass transform(final CtClass clazz) throws CannotCompileException {\n        clazz.instrument(new PowerMockExpressionEditor(getStrategy(), clazz, mockGetawayClass));\n        return clazz;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/JavassistMockTransformerChainFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.MockTransformerChain;\nimport org.powermock.core.transformers.MockTransformerChainFactory;\nimport org.powermock.core.transformers.TransformStrategy;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain.MockTransformerChainBuilder;\n\nimport java.util.List;\n\npublic class JavassistMockTransformerChainFactory implements MockTransformerChainFactory {\n    \n    private static final TransformStrategy DEFAULT = TransformStrategy.CLASSLOADER;\n    \n    @Override\n    public MockTransformerChain createDefaultChain() {\n        return createDefaultChain(DEFAULT);\n    }\n    \n    @Override\n    public MockTransformerChain createDefaultChain(final TransformStrategy transformStrategy) {\n        return createDefaultChainBuilder(transformStrategy).build();\n    }\n    \n    @Override\n    public MockTransformerChain createDefaultChain(final List<MockTransformer> extraMockTransformers) {\n        return createDefaultChainBuilder(DEFAULT)\n                   .append(extraMockTransformers)\n                   .build();\n    }\n    \n    @Override\n    public MockTransformerChain createTestClassChain(final MockTransformer testClassTransformer) {\n        return createDefaultChainBuilder(DEFAULT)\n                   .append(testClassTransformer)\n                   .build();\n    }\n    \n    private MockTransformerChainBuilder createDefaultChainBuilder(final TransformStrategy transformStrategy) {\n        return DefaultMockTransformerChain.newBuilder()\n                                          .append(new ClassFinalModifierMockTransformer(transformStrategy))\n                                          .append(new ConstructorsMockTransformer(transformStrategy))\n                                          .append(new InstrumentMockTransformer(transformStrategy))\n                                          .append(new PackagePrivateClassesMockTransformer(transformStrategy))\n                                          .append(new StaticFinalFieldsMockTransformer(transformStrategy))\n                                          .append(new StaticFinalNativeMethodMockTransformer(transformStrategy))\n                                          .append(new SuppressStaticInitializerMockTransformer(transformStrategy))\n                                          .append(new MethodSizeMockTransformer(transformStrategy));\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CannotCompileException;\nimport javassist.CtClass;\nimport javassist.CtMethod;\nimport javassist.Modifier;\nimport javassist.NotFoundException;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.transformers.TransformStrategy;\n\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.VOID;\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.getCorrectReturnValueType;\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.getReturnTypeAsString;\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.shouldSkipMethod;\n\nabstract class MethodMockTransformer extends AbstractJavaAssistMockTransformer {\n    \n    private Class<?> mockGetawayClass;\n    \n    MethodMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n        this.mockGetawayClass = MockGateway.class;\n    }\n    \n    void modifyMethod(final CtMethod method) throws NotFoundException, CannotCompileException {\n        \n        if (!shouldSkipMethod(method)) {\n            \n            // Lookup the method return type\n            \n            final CtClass returnTypeAsCtClass = method.getReturnType();\n            final String returnTypeAsString = getReturnTypeAsString(method);\n            \n            if (Modifier.isNative(method.getModifiers())) {\n                modifyNativeMethod(method, returnTypeAsCtClass, returnTypeAsString);\n            } else {\n                modifyMethod(method, returnTypeAsCtClass, returnTypeAsString);\n            }\n        }\n    }\n    \n    \n    private void modifyNativeMethod(CtMethod method, CtClass returnTypeAsCtClass,\n                                    String returnTypeAsString) throws CannotCompileException {\n        String methodName = method.getName();\n        String returnValue = \"($r)value\";\n        \n        if (returnTypeAsCtClass.equals(CtClass.voidType)) {\n            returnValue = VOID;\n        }\n        \n        String classOrInstance = classOrInstance(method);\n        method.setModifiers(method.getModifiers() - Modifier.NATIVE);\n        String code = \"Object value = \"\n                          + mockGetawayClass.getName()\n                          + \".methodCall(\"\n                          + classOrInstance\n                          + \", \\\"\"\n                          + method.getName()\n                          + \"\\\", $args, $sig, \\\"\"\n                          + returnTypeAsString\n                          + \"\\\");\"\n                          + \"if (value != \"\n                          + MockGateway.class.getName() + \".PROCEED) \"\n                          + \"return \"\n                          + returnValue + \"; \"\n                          + \"throw new java.lang.UnsupportedOperationException(\\\"\" + methodName + \" is native\\\");\";\n        method.setBody(\"{\" + code + \"}\");\n    }\n    \n    private String classOrInstance(CtMethod method) {\n        String classOrInstance = \"this\";\n        if (Modifier.isStatic(method.getModifiers())) {\n            classOrInstance = \"$class\";\n        }\n        return classOrInstance;\n    }\n    \n    private void modifyMethod(CtMethod method, CtClass returnTypeAsCtClass,\n                              String returnTypeAsString) throws CannotCompileException {\n        final String returnValue = getCorrectReturnValueType(returnTypeAsCtClass);\n        \n        String classOrInstance = classOrInstance(method);\n        \n        String code = \"Object value = \"\n                          + mockGetawayClass.getName()\n                          + \".methodCall(\"\n                          + classOrInstance + \", \\\"\"\n                          + method.getName()\n                          + \"\\\", $args, $sig, \\\"\"\n                          + returnTypeAsString\n                          + \"\\\");\"\n                          + \"if (value != \" + MockGateway.class.getName() + \".PROCEED) \" + \"return \"\n                          + returnValue + \"; \";\n        \n        method.insertBefore(\"{ \" + code + \"}\");\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodSizeMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CannotCompileException;\nimport javassist.CtClass;\nimport javassist.CtMethod;\nimport javassist.NotFoundException;\nimport javassist.bytecode.CodeAttribute;\nimport org.powermock.core.transformers.TransformStrategy;\n\n/**\n * According to JVM specification method size must be lower than 65536 bytes.\n * When that limit is exceeded class loader will fail to load the class.\n * Since instrumentation can increase method size significantly it must be\n * ensured that JVM limit is not exceeded.\n * <p/>\n * When the limit is exceeded method's body is replaced by exception throw.\n * Method is then instrumented again to allow mocking and suppression.\n *\n * @see <a href=\"http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.3\">JVM specification</a>\n */\npublic class MethodSizeMockTransformer extends MethodMockTransformer {\n    \n    private static final int MAX_METHOD_CODE_LENGTH_LIMIT = 65536;\n    \n    public MethodSizeMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n    }\n    \n    public CtClass transform(final CtClass clazz) throws CannotCompileException, NotFoundException {\n        for (CtMethod method : clazz.getDeclaredMethods()) {\n            if (isMethodSizeExceeded(method)) {\n                String code = \"{throw new IllegalAccessException(\\\"\" +\n                                  \"Method was too large and after instrumentation exceeded JVM limit. \" +\n                                  \"PowerMock modified the method to allow JVM to load the class. \" +\n                                  \"You can use PowerMock API to suppress or mock this method behaviour.\" +\n                                  \"\\\");}\";\n                method.setBody(code);\n                modifyMethod(method);\n            }\n        }\n        return clazz;\n    }\n    \n    private boolean isMethodSizeExceeded(CtMethod method) {\n        CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute();\n        return codeAttribute != null && codeAttribute.getCodeLength() >= MAX_METHOD_CODE_LENGTH_LIMIT;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/PackagePrivateClassesMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CtClass;\nimport javassist.Modifier;\nimport javassist.NotFoundException;\nimport org.powermock.core.transformers.TransformStrategy;\n\nimport static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE;\n\n/**\n * Set class modifier to public to allow for mocking of package private\n * classes. This is needed because we've changed to CgLib naming policy\n * to allow for mocking of signed classes.\n */\npublic class PackagePrivateClassesMockTransformer extends AbstractJavaAssistMockTransformer {\n    \n    public PackagePrivateClassesMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n    }\n    \n    @Override\n    public CtClass transform(final CtClass clazz) {\n        final String name = clazz.getName();\n        if (getStrategy() != INST_REDEFINE) {\n            transform(clazz, name);\n        }\n        return clazz;\n    }\n    \n    private static void transform(final CtClass clazz, final String name) {\n        try {\n            final int modifiers = clazz.getModifiers();\n            if (Modifier.isPackage(modifiers)) {\n                if (isNotSystemClass(name) && !(clazz.isInterface() && clazz.getDeclaringClass() != null)) {\n                    clazz.setModifiers(Modifier.setPublic(modifiers));\n                }\n            }\n        } catch (NotFoundException e) {\n            // OK, continue\n        }\n    }\n    \n    private static boolean isNotSystemClass(final String name) {\n        return !name.startsWith(\"java.\");\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalFieldsMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CtClass;\nimport javassist.CtField;\nimport javassist.Modifier;\nimport org.powermock.core.transformers.TransformStrategy;\n\nimport static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE;\n\n\n/**\n * Remove final from all static final fields. Not possible if using a java agent.\n */\npublic class StaticFinalFieldsMockTransformer extends AbstractJavaAssistMockTransformer {\n    \n    public StaticFinalFieldsMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n    }\n    \n    public CtClass transform(final CtClass clazz) {\n        if (clazz.isInterface()) {\n            return clazz;\n        }\n        \n        if (getStrategy() != INST_REDEFINE) {\n            for (CtField f : clazz.getDeclaredFields()) {\n                final int modifiers = f.getModifiers();\n                if (Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)) {\n                    f.setModifiers(modifiers ^ Modifier.FINAL);\n                }\n            }\n        }\n        return clazz;\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalNativeMethodMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CannotCompileException;\nimport javassist.CtClass;\nimport javassist.CtMethod;\nimport javassist.NotFoundException;\nimport org.powermock.core.transformers.TransformStrategy;\n\n\npublic class StaticFinalNativeMethodMockTransformer extends MethodMockTransformer {\n    \n    public StaticFinalNativeMethodMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n    }\n    \n    @Override\n    public CtClass transform(final CtClass clazz) throws NotFoundException, CannotCompileException {\n            for (CtMethod m : clazz.getDeclaredMethods()) {\n                modifyMethod(m);\n            }\n        return clazz;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/SuppressStaticInitializerMockTransformer.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist;\n\nimport javassist.CannotCompileException;\nimport javassist.CtClass;\nimport javassist.CtConstructor;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.transformers.TransformStrategy;\n\nimport static org.powermock.core.transformers.TransformStrategy.CLASSLOADER;\n\npublic class SuppressStaticInitializerMockTransformer extends AbstractJavaAssistMockTransformer {\n    \n    public SuppressStaticInitializerMockTransformer(final TransformStrategy strategy) {\n        super(strategy);\n    }\n    \n    @Override\n    public CtClass transform(final CtClass clazz) throws CannotCompileException {\n        if (getStrategy() == CLASSLOADER) {\n            if (MockGateway.staticConstructorCall(clazz.getName()) != MockGateway.PROCEED) {\n                CtConstructor classInitializer = clazz.makeClassInitializer();\n                classInitializer.setBody(\"{}\");\n            }\n        }\n        return clazz;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/JavaAssistClassWrapperFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist.support;\n\nimport javassist.CtClass;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.ClassWrapperFactory;\n\npublic class JavaAssistClassWrapperFactory implements ClassWrapperFactory<CtClass> {\n    @Override\n    public ClassWrapper<CtClass> wrap(CtClass ctClass) {\n        return new JavaAssistClassWrapper(ctClass);\n    }\n    \n    public static class JavaAssistClassWrapper implements ClassWrapper<CtClass> {\n        \n        private final CtClass ctClass;\n        \n        private JavaAssistClassWrapper(CtClass ctClass) {\n            this.ctClass = ctClass;\n        }\n        \n        @Override\n        public boolean isInterface() {\n            return ctClass.isInterface();\n        }\n        \n        @Override\n        public CtClass unwrap() {\n            return ctClass;\n        }\n\n        @Override\n        public ClassWrapper<CtClass> wrap(final CtClass original) {\n            return new JavaAssistClassWrapper(original);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist.support;\n\nimport javassist.CannotCompileException;\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport javassist.CtField;\nimport javassist.CtMethod;\nimport javassist.CtNewConstructor;\nimport javassist.NotFoundException;\nimport javassist.bytecode.DuplicateMemberException;\nimport javassist.bytecode.FieldInfo;\nimport javassist.expr.ConstructorCall;\nimport javassist.expr.ExprEditor;\nimport javassist.expr.FieldAccess;\nimport javassist.expr.MethodCall;\nimport javassist.expr.NewExpr;\nimport org.powermock.core.IndicateReloadClass;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.transformers.TransformStrategy;\n\nimport static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE;\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.VOID;\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.getCorrectReturnValueType;\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.getReturnTypeAsString;\nimport static org.powermock.core.transformers.javassist.support.TransformerHelper.isNotSyntheticField;\n\npublic final class PowerMockExpressionEditor extends ExprEditor {\n    \n    private final CtClass clazz;\n    private final Class<?> mockGetawayClass;\n    private final TransformStrategy strategy;\n    \n    public PowerMockExpressionEditor(final TransformStrategy strategy, final CtClass clazz, final Class<?> mockGetawayClass) {\n        this.strategy = strategy;\n        this.clazz = clazz;\n        this.mockGetawayClass = mockGetawayClass;\n    }\n    \n    @Override\n    public void edit(NewExpr e) throws CannotCompileException {\n        String code = \"Object instance =\" +\n                          MockGateway.class.getName() +\n                          \".newInstanceCall($type,$args,$sig);\" +\n                          \"if(instance != \" + MockGateway.class.getName() + \".PROCEED) {\" +\n                          \"\tif(instance instanceof java.lang.reflect.Constructor) {\"\n                          +\n                          \"\t\t$_ = ($r) sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization($type, java.lang.Object.class.getDeclaredConstructor(null)).newInstance(null);\" +\n                          \"\t} else {\" +\n                          \"\t\t$_ = ($r) instance;\" +\n                          \"\t}\" +\n                          \"} else {\" +\n                          \"\t$_ = $proceed($$);\" +\n                          \"}\";\n        // TODO Change to objenisis instead\n        e.replace(code);\n    }\n    \n    @Override\n    public void edit(MethodCall m) throws CannotCompileException {\n        try {\n            final CtMethod method = m.getMethod();\n            final CtClass declaringClass = method.getDeclaringClass();\n            \n            if (declaringClass != null) {\n                if (TransformerHelper.shouldTreatAsSystemClassCall(declaringClass)) {\n                    StringBuilder code = new StringBuilder();\n                    code.append(\"{Object classOrInstance = null; if($0!=null){classOrInstance = $0;} else { classOrInstance = $class;}\");\n                    code.append(\"Object value =  \")\n                        .append(MockGateway.class.getName())\n                        .append(\".methodCall(\")\n                        .append(\"classOrInstance,\\\"\")\n                        .append(m.getMethodName())\n                        .append(\"\\\",$args, $sig,\\\"\")\n                        .append(getReturnTypeAsString(method))\n                        .append(\"\\\");\");\n                    code.append(\"if(value == \").append(MockGateway.class.getName()).append(\".PROCEED) {\");\n                    code.append(\"\t$_ = $proceed($$);\");\n                    code.append(\"} else {\");\n                    final String correctReturnValueType = getCorrectReturnValueType(method.getReturnType());\n                    if (!VOID.equals(correctReturnValueType)) {\n                        code.append(\"\t$_ = \").append(correctReturnValueType).append(\";\");\n                    }\n                    code.append(\"}}\");\n                    m.replace(code.toString());\n                }\n            }\n        } catch (NotFoundException e) {\n                /*\n                 * If multiple java agents are active (in INST_REDEFINE mode), the types implicitly loaded by javassist from disk\n                 * might differ from the types available in memory. Thus, this error might occur.\n                 *\n                 * It may also happen if PowerMock is modifying an SPI where the SPI require some classes to be available in the classpath\n                 * at runtime but they are not! This is valid in some cases such as slf4j.\n                 */\n        }\n    }\n    \n    @Override\n    public void edit(ConstructorCall c) throws CannotCompileException {\n        /*\n         * Note that constructor call only intercepts calls to super or this\n         * from an instantiated class. This means that A a = new A(); will\n         * NOT trigger a ConstructorCall for the default constructor in A.\n         * If A where to extend B and A's constructor only delegates to\n         * super(), the default constructor of B would trigger a\n         * ConstructorCall. This means that we need to handle\n         * \"suppressConstructorCode\" both here and in NewExpr.\n         */\n        if (strategy != INST_REDEFINE && !c.getClassName().startsWith(\"java.lang\")) {\n            final CtClass superclass;\n            try {\n                superclass = clazz.getSuperclass();\n            } catch (NotFoundException e) {\n                throw new RuntimeException(e);\n            }\n\n            /*\n             * Create a default constructor in the super class if it doesn't\n             * exist. This is needed because if the code in the current\n             * constructor should be suppressed (which we don't know at this\n             * moment of time) the parent class must have a default\n             * constructor that we can delegate to.\n             */\n            addNewDeferConstructor(clazz);\n            final StringBuilder code = new StringBuilder();\n            code.append(\"{Object value =\")\n                .append(mockGetawayClass.getName())\n                .append(\".constructorCall($class, $args, $sig);\");\n            code.append(\"if (value != \").append(MockGateway.class.getName()).append(\".PROCEED){\");\n\n            /*\n             * TODO Suppress and lazy inject field (when this feature is ready).\n             */\n            if (superclass.getName().equals(Object.class.getName())) {\n                code.append(\" super();\");\n            } else {\n                code.append(\" super((\").append(IndicateReloadClass.class.getName()).append(\") null);\");\n            }\n            code.append(\"} else {\");\n            code.append(\"   $proceed($$);\");\n            code.append(\"}}\");\n            c.replace(code.toString());\n        }\n    }\n    \n    @Override\n    public void edit(FieldAccess f) throws CannotCompileException {\n        if (f.isReader()) {\n            CtClass returnTypeAsCtClass;\n            FieldInfo fieldInfo;\n            \n            try {\n                CtField field = f.getField();\n                returnTypeAsCtClass = field.getType();\n                fieldInfo = field.getFieldInfo2();\n            } catch (NotFoundException e) {\n                    /*\n                     * If multiple java agents are active (in INST_REDEFINE mode), the types implicitly loaded by javassist from disk\n                     * might differ from the types available in memory. Thus, this error might occur.\n                     *\n                     * It may also happen if PowerMock is modifying an SPI where the SPI require some classes to be available in the classpath\n                     * at runtime but they are not! This is valid in some cases such as slf4j.\n                     */\n                return;\n            }\n            \n            if (isNotSyntheticField(fieldInfo)) {\n                String code = \"{Object value =  \" +\n                                  MockGateway.class.getName() +\n                                  \".fieldCall(\" +\n                                  \"$0,$class,\\\"\" +\n                                  f.getFieldName() +\n                                  \"\\\",$type);\" +\n                                  \"if(value == \" + MockGateway.class.getName() + \".PROCEED) {\" +\n                                  \"\t$_ = $proceed($$);\" +\n                                  \"} else {\" +\n                                  \"\t$_ = \" + getCorrectReturnValueType(returnTypeAsCtClass) + \";\" +\n                                  \"}}\";\n                f.replace(code);\n            }\n        }\n    }\n    \n    /**\n     * Create a defer constructor in the class which will be called when the\n     * constructor is suppressed.\n     *\n     * @param clazz The class whose super constructor will get a new defer\n     *              constructor if it doesn't already have one.\n     * @throws CannotCompileException If an unexpected compilation error occurs.\n     */\n    private void addNewDeferConstructor(final CtClass clazz) throws CannotCompileException {\n        final CtClass superClass;\n        try {\n            superClass = clazz.getSuperclass();\n        } catch (NotFoundException e1) {\n            throw new IllegalArgumentException(\"Internal error: Failed to get superclass for \" + clazz.getName() + \" when about to create a new default constructor.\");\n        }\n        \n        ClassPool classPool = clazz.getClassPool();\n        /*\n         * To make a unique defer constructor we create a new constructor\n         * with one argument (IndicateReloadClass). So we get this class a\n         * Javassist class below.\n         */\n        final CtClass constructorType;\n        try {\n            constructorType = classPool.get(IndicateReloadClass.class.getName());\n        } catch (NotFoundException e) {\n            throw new IllegalArgumentException(\"Internal error: failed to get the \" + IndicateReloadClass.class.getName()\n                                                   + \" when added defer constructor.\");\n        }\n        clazz.defrost();\n        if (superClass.getName().equals(Object.class.getName())) {\n            try {\n                clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], \"{super();}\", clazz));\n            } catch (DuplicateMemberException e) {\n                // OK, the constructor has already been added.\n            }\n        } else {\n            addNewDeferConstructor(superClass);\n            try {\n                clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], \"{super($$);}\", clazz));\n            } catch (DuplicateMemberException e) {\n                // OK, the constructor has already been added.\n            }\n        }\n    }\n    \n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/Primitives.java",
    "content": "/*\n * Copyright 2015 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.transformers.javassist.support;\n\nimport javassist.CtPrimitiveType;\n\nimport java.util.Collections;\nimport java.util.IdentityHashMap;\nimport java.util.Map;\n\nimport static javassist.CtClass.booleanType;\nimport static javassist.CtClass.byteType;\nimport static javassist.CtClass.charType;\nimport static javassist.CtClass.doubleType;\nimport static javassist.CtClass.floatType;\nimport static javassist.CtClass.intType;\nimport static javassist.CtClass.longType;\nimport static javassist.CtClass.shortType;\nimport static javassist.CtClass.voidType;\n\n/**\n * Simple utility that maps constant fields of {@link javassist.CtClass} to\n * their corresponding java class-objects for primitive types.\n */\npublic class Primitives {\n    \n    private static final Map<CtPrimitiveType, Class<?>> ct2primitiveClass =\n        lookupMappings();\n    \n    private static Map<CtPrimitiveType, Class<?>> lookupMappings() {\n        Map<CtPrimitiveType, Class<?>> mappings = new IdentityHashMap<CtPrimitiveType, Class<?>>(10);\n        for (Object[] each : new Object[][]{\n            {booleanType, boolean.class},\n            {byteType, byte.class},\n            {charType, char.class},\n            {doubleType, double.class},\n            {floatType, float.class},\n            {intType, int.class},\n            {longType, long.class},\n            {shortType, short.class},\n            {voidType, void.class}\n        }) {\n            mappings.put((CtPrimitiveType) each[0], (Class<?>) each[1]);\n        }\n        return Collections.unmodifiableMap(mappings);\n    }\n    \n    public static Class<?> getClassFor(CtPrimitiveType ctPrimitiveType) {\n        return ct2primitiveClass.get(ctPrimitiveType);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/TransformerHelper.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.javassist.support;\n\nimport javassist.CtClass;\nimport javassist.CtMethod;\nimport javassist.Modifier;\nimport javassist.NotFoundException;\nimport javassist.bytecode.AccessFlag;\nimport javassist.bytecode.FieldInfo;\n\npublic class TransformerHelper {\n    \n    public static final String VOID = \"\";\n    \n    private static boolean isAccessFlagSynthetic(CtMethod method) {\n        int accessFlags = method.getMethodInfo2().getAccessFlags();\n        return ((accessFlags & AccessFlag.SYNTHETIC) != 0) && !isBridgeMethod(method);\n    }\n    \n    private static boolean isBridgeMethod(CtMethod method) {\n        return (method.getMethodInfo2()\n                      .getAccessFlags() & AccessFlag.BRIDGE) != 0;\n    }\n    \n    /**\n     * @return The correct return type, i.e. takes care of casting the a wrapper\n     * type to primitive type if needed.\n     */\n    public static String getCorrectReturnValueType(final CtClass returnTypeAsCtClass) {\n        final String returnTypeAsString = returnTypeAsCtClass.getName();\n        final String returnValue;\n        if (returnTypeAsCtClass.equals(CtClass.voidType)) {\n            returnValue = VOID;\n        } else if (returnTypeAsCtClass.isPrimitive()) {\n            if (returnTypeAsString.equals(\"char\")) {\n                returnValue = \"((java.lang.Character)value).charValue()\";\n            } else if (returnTypeAsString.equals(\"boolean\")) {\n                returnValue = \"((java.lang.Boolean)value).booleanValue()\";\n            } else {\n                returnValue = \"((java.lang.Number)value).\" + returnTypeAsString + \"Value()\";\n            }\n        } else {\n            returnValue = \"(\" + returnTypeAsString + \")value\";\n        }\n        return returnValue;\n    }\n    \n    public static boolean isNotSyntheticField(FieldInfo fieldInfo) {\n        return (fieldInfo.getAccessFlags() & AccessFlag.SYNTHETIC) == 0;\n    }\n    \n    public static boolean shouldSkipMethod(CtMethod method) {\n        return isAccessFlagSynthetic(method) || Modifier.isAbstract(method.getModifiers());\n    }\n    \n    public static String getReturnTypeAsString(final CtMethod method) throws NotFoundException {\n        CtClass returnType = method.getReturnType();\n        String returnTypeAsString = VOID;\n        if (!returnType.equals(CtClass.voidType)) {\n            returnTypeAsString = returnType.getName();\n        }\n        return returnTypeAsString;\n    }\n    \n    public static boolean shouldTreatAsSystemClassCall(CtClass declaringClass) {\n        final String className = declaringClass.getName();\n        return className.startsWith(\"java.\");\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/ForMethodsJavaAssistTestClassTransformer.java",
    "content": "package org.powermock.core.transformers.javassist.testclass;\n\nimport javassist.CtMethod;\nimport org.powermock.core.transformers.MethodSignatureWriter;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\n\npublic class ForMethodsJavaAssistTestClassTransformer extends JavaAssistTestClassTransformer {\n    \n    private final Collection<Method> testMethodsThatRunOnOtherClassLoaders;\n    /**\n     * Is lazily initilized because of\n     * AbstractTestSuiteChunkerImpl#chunkClass(Class)\n     */\n    private Collection<String> methodsThatRunOnOtherClassLoaders;\n    \n    public ForMethodsJavaAssistTestClassTransformer(final Class<?> testClass,\n                                                    final Class<? extends Annotation> testMethodAnnotation,\n                                                    final MethodSignatureWriter<CtMethod> methodSignatureWriter,\n                                                    final Collection<Method> testMethodsThatRunOnOtherClassLoaders) {\n        super(testClass, testMethodAnnotation, methodSignatureWriter);\n        this.testMethodsThatRunOnOtherClassLoaders = testMethodsThatRunOnOtherClassLoaders;\n    }\n    \n    @Override\n    protected boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception {\n        if (null == methodsThatRunOnOtherClassLoaders) {\n            /* This lazy initialization is necessary - see above */\n            methodsThatRunOnOtherClassLoaders = new HashSet<String>();\n            for (Method m : testMethodsThatRunOnOtherClassLoaders) {\n                methodsThatRunOnOtherClassLoaders.add(signatureOf(m));\n            }\n            testMethodsThatRunOnOtherClassLoaders.clear();\n        }\n        return methodsThatRunOnOtherClassLoaders.contains(signatureOf(method));\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/FromAllMethodsExceptJavaAssistTestClassTransformer.java",
    "content": "package org.powermock.core.transformers.javassist.testclass;\n\nimport javassist.CtMethod;\nimport org.powermock.core.transformers.MethodSignatureWriter;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\npublic class FromAllMethodsExceptJavaAssistTestClassTransformer extends JavaAssistTestClassTransformer {\n    private final String targetMethodSignature;\n    \n    public FromAllMethodsExceptJavaAssistTestClassTransformer(final Class<?> testClass,\n                                                              final Class<? extends Annotation> testMethodAnnotation,\n                                                              final MethodSignatureWriter<CtMethod> signatureWriter,\n                                                              final Method methodToExclude) {\n        super(testClass, testMethodAnnotation, signatureWriter);\n        this.targetMethodSignature = signatureWriter.signatureForReflection(methodToExclude);\n    }\n    \n    @Override\n    protected boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception {\n        return !signatureOf(method).equals(targetMethodSignature);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/JavaAssistTestClassTransformer.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.core.transformers.javassist.testclass;\n\nimport javassist.CannotCompileException;\nimport javassist.CtClass;\nimport javassist.CtConstructor;\nimport javassist.CtMethod;\nimport javassist.CtPrimitiveType;\nimport javassist.Modifier;\nimport javassist.NotFoundException;\nimport javassist.bytecode.AnnotationsAttribute;\nimport org.powermock.core.IndicateReloadClass;\nimport org.powermock.core.testlisteners.GlobalNotificationBuildSupport;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.MethodSignatureWriter;\nimport org.powermock.core.transformers.TestClassTransformer;\nimport org.powermock.core.transformers.javassist.support.Primitives;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Array;\n\npublic abstract class JavaAssistTestClassTransformer extends TestClassTransformer<CtClass, CtMethod> {\n    \n    JavaAssistTestClassTransformer(Class<?> testClass,\n                                   Class<? extends Annotation> testMethodAnnotationType,\n                                   MethodSignatureWriter<CtMethod> signatureWriter) {\n        super(testClass, testMethodAnnotationType, signatureWriter);\n    }\n    \n    protected abstract boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception;\n    \n    @Override\n    public ClassWrapper<CtClass> transform(final ClassWrapper<CtClass> clazz) throws Exception {\n            transform(clazz.unwrap());\n            return clazz;\n    }\n    \n    private void transform(final CtClass clazz) throws Exception {\n        if (clazz.isFrozen()) {\n            clazz.defrost();\n        }\n        \n        if (isTestClass(clazz)) {\n            removeTestAnnotationsForTestMethodsThatRunOnOtherClassLoader(clazz);\n            addLifeCycleNotifications(clazz);\n            makeDeferConstructorNonPublic(clazz);\n            restoreOriginalConstructorsAccesses(clazz);\n            \n        } else if (isNestedWithinTestClass(clazz)) {\n            makeDeferConstructorNonPublic(clazz);\n            restoreOriginalConstructorsAccesses(clazz);\n        }\n    \n    }\n    \n    private boolean isTestClass(CtClass clazz) {\n        try {\n            return Class.forName(clazz.getName(), false, getTestClass().getClassLoader())\n                        .isAssignableFrom(getTestClass());\n        } catch (ClassNotFoundException ex) {\n            return false;\n        }\n    }\n    \n    private boolean isNestedWithinTestClass(CtClass clazz) {\n        String clazzName = clazz.getName();\n        return clazzName.startsWith(getTestClass().getName())\n                   && '$' == clazzName.charAt(getTestClass().getName().length());\n    }\n    \n    private Class<?> asOriginalClass(CtClass type) throws Exception {\n        try {\n            return type.isArray()\n                       ? Array.newInstance(asOriginalClass(type.getComponentType()), 0).getClass()\n                       : type.isPrimitive()\n                             ? Primitives.getClassFor((CtPrimitiveType) type)\n                             : Class.forName(type.getName(), true, getTestClass().getClassLoader());\n        } catch (Exception ex) {\n            throw new RuntimeException(\"Cannot resolve type: \" + type, ex);\n        }\n    }\n    \n    private Class<?>[] asOriginalClassParams(CtClass[] parameterTypes)\n        throws Exception {\n        final Class<?>[] classParams = new Class[parameterTypes.length];\n        for (int i = 0; i < classParams.length; ++i) {\n            classParams[i] = asOriginalClass(parameterTypes[i]);\n        }\n        return classParams;\n    }\n    \n    private void removeTestMethodAnnotationFrom(CtMethod m) {\n        final AnnotationsAttribute attr = (AnnotationsAttribute)\n                                              m.getMethodInfo().getAttribute(AnnotationsAttribute.visibleTag);\n        javassist.bytecode.annotation.Annotation[] newAnnotations =\n            new javassist.bytecode.annotation.Annotation[attr.numAnnotations() - 1];\n        int i = -1;\n        for (javassist.bytecode.annotation.Annotation a : attr.getAnnotations()) {\n            if (a.getTypeName().equals(getTestMethodAnnotationType().getName())) {\n                continue;\n            }\n            newAnnotations[++i] = a;\n        }\n        attr.setAnnotations(newAnnotations);\n    }\n    \n    private void removeTestAnnotationsForTestMethodsThatRunOnOtherClassLoader(CtClass clazz)\n        throws Exception {\n        for (CtMethod m : clazz.getDeclaredMethods()) {\n            if (m.hasAnnotation(getTestMethodAnnotationType()) && mustHaveTestAnnotationRemoved(m)) {\n                removeTestMethodAnnotationFrom(m);\n            }\n        }\n    }\n    \n    private void addLifeCycleNotifications(CtClass clazz) {\n        try {\n            addClassInitializerNotification(clazz);\n            addConstructorNotification(clazz);\n        } catch (CannotCompileException ex) {\n            throw new Error(\"Powermock error: \" + ex.getMessage(), ex);\n        }\n    }\n    \n    private void addClassInitializerNotification(CtClass clazz)\n        throws CannotCompileException {\n        if (null == clazz.getClassInitializer()) {\n            clazz.makeClassInitializer();\n        }\n        clazz.getClassInitializer().insertBefore(\n            GlobalNotificationBuildSupport.class.getName()\n                + \".testClassInitiated(\" + clazz.getName() + \".class);\");\n    }\n    \n    private static boolean hasSuperClass(CtClass clazz) {\n        try {\n            CtClass superClazz = clazz.getSuperclass();\n            /*\n             * Being extra careful here - and backup in case the\n             * work-in-progress clazz doesn't cause NotFoundException ...\n             */\n            return null != superClazz\n                       && !\"java.lang.Object\".equals(superClazz.getName());\n        } catch (NotFoundException noWasSuperClassFound) {\n            return false;\n        }\n    }\n    \n    private void addConstructorNotification(final CtClass clazz)\n        throws CannotCompileException {\n        final String notificationCode =\n            GlobalNotificationBuildSupport.class.getName()\n                + \".testInstanceCreated(this);\";\n        final boolean asFinally = !hasSuperClass(clazz);\n        for (final CtConstructor constr : clazz.getDeclaredConstructors()) {\n            constr.insertAfter(\n                notificationCode,\n                asFinally/* unless there is a super-class, because of this\n                              * problem: https://community.jboss.org/thread/94194*/);\n        }\n    }\n    \n    private void restoreOriginalConstructorsAccesses(CtClass clazz) throws Exception {\n        Class<?> originalClass = getTestClass().getName().equals(clazz.getName())\n                                     ? getTestClass()\n                                     : Class.forName(clazz.getName(), true, getTestClass().getClassLoader());\n        for (final CtConstructor ctConstr : clazz.getConstructors()) {\n            int ctModifiers = ctConstr.getModifiers();\n            if (!Modifier.isPublic(ctModifiers)) {\n                /* Probably a defer-constructor */\n                continue;\n            }\n            int desiredAccessModifiers = originalClass.getDeclaredConstructor(\n                asOriginalClassParams(ctConstr.getParameterTypes())).getModifiers();\n            \n            if (Modifier.isPrivate(desiredAccessModifiers)) {\n                ctConstr.setModifiers(Modifier.setPrivate(ctModifiers));\n            } else if (Modifier.isProtected(desiredAccessModifiers)) {\n                ctConstr.setModifiers(Modifier.setProtected(ctModifiers));\n            } else if (!Modifier.isPublic(desiredAccessModifiers)) {\n                ctConstr.setModifiers(Modifier.setPackage(ctModifiers));\n            } else {\n                /* ctConstr remains public */\n            }\n        }\n    }\n    \n    private void makeDeferConstructorNonPublic(final CtClass clazz) {\n        for (final CtConstructor constr : clazz.getConstructors()) {\n            try {\n                for (CtClass paramType : constr.getParameterTypes()) {\n                    if (IndicateReloadClass.class.getName()\n                                                 .equals(paramType.getName())) {\n                        /* Found defer constructor ... */\n                        final int modifiers = constr.getModifiers();\n                        if (Modifier.isPublic(modifiers)) {\n                            constr.setModifiers(Modifier.setProtected(modifiers));\n                        }\n                        break;\n                    }\n                }\n            } catch (NotFoundException thereAreNoParameters) {\n                /* ... but to get an exception here seems odd. */\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/support/DefaultMockTransformerChain.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers.support;\n\n\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.MockTransformerChain;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class DefaultMockTransformerChain implements MockTransformerChain {\n    \n    private final List<MockTransformer> transformers;\n    \n    private DefaultMockTransformerChain(final List<MockTransformer> transformers) {\n        this.transformers = Collections.unmodifiableList(transformers);\n    }\n    \n    @Override\n    public <T> ClassWrapper<T> transform(final ClassWrapper<T> clazz) throws Exception {\n        ClassWrapper<T> classWrapper = clazz;\n        for (MockTransformer transformer : transformers) {\n            classWrapper = transformer.transform(classWrapper);\n        }\n        return classWrapper;\n    }\n    \n    @Override\n    public Collection<MockTransformer> filter(final FilterPredicate predicate) {\n        final ArrayList<MockTransformer> filtered = new ArrayList<MockTransformer>();\n        \n        for (MockTransformer transformer : transformers) {\n            if (predicate.test(transformer)) {\n                filtered.add(transformer);\n            }\n        }\n        \n        return filtered;\n    }\n    \n    @Override\n    public String toString() {\n        return \"MockTransformerChain{\" + \"transformers=\" + transformers + '}';\n    }\n    \n    public static MockTransformerChainBuilder newBuilder() {\n        return new MockTransformerChainBuilder();\n    }\n    \n    public static class MockTransformerChainBuilder {\n        \n        private final List<MockTransformer> transformers;\n        \n        private MockTransformerChainBuilder() {\n            transformers = new ArrayList<MockTransformer>();\n        }\n        \n        public MockTransformerChainBuilder append(MockTransformer transformer) {\n            transformers.add(transformer);\n            return this;\n        }\n        \n        public MockTransformerChainBuilder append(final List<MockTransformer> mockTransformerChain) {\n            transformers.addAll(mockTransformerChain);\n            return this;\n        }\n        \n        public MockTransformerChain build() {\n            return new DefaultMockTransformerChain(transformers);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/core/transformers/support/FilterPredicates.java",
    "content": "package org.powermock.core.transformers.support;\n\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.MockTransformerChain.FilterPredicate;\n\npublic class FilterPredicates {\n    \n    public static FilterPredicate isInstanceOf(final Class<?> klass) {\n        return new FilterPredicate() {\n            @Override\n            public boolean test(final MockTransformer<?> mockTransformer) {\n                return klass.isAssignableFrom(mockTransformer.getClass());\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/mockpolicies/MockPolicyClassLoadingSettings.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.mockpolicies;\n\n/**\n * Contains class-loading related settings. PowerMock uses the information\n * stored in this object to configure it's mock classloader to allow for\n * testability.\n * <p>\n * Since mock policies can be chained subsequent policies can override behavior\n * of a previous policy. To avoid accidental overrides it's recommended\n * <i>add</i> behavior instead of <i>setting</i> behavior since the latter\n * overrides all previous configurations.\n */\npublic interface MockPolicyClassLoadingSettings {\n\n\t/**\n\t * Set which static initializers to suppress. Note that this overrides all\n\t * previous configurations.\n\t */\n\tvoid setStaticInitializersToSuppress(String[] staticInitializersToSuppress);\n\n\t/**\n\t * Add static initializers to suppress.\n\t */\n\tvoid addStaticInitializersToSuppress(String firstStaticInitializerToSuppress, String... additionalStaticInitializersToSuppress);\n\n\t/**\n\t * Add static initializers to suppress.\n\t */\n\tvoid addStaticInitializersToSuppress(String[] staticInitializersToSuppress);\n\n\t/**\n\t * Set which types that should be loaded (and possibly modified) by the mock\n\t * classloader. Note that this overrides all previous configurations.\n\t */\n\tvoid setFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes);\n\n\t/**\n\t * Add types that should be loaded (and possibly modified) by the mock\n\t * classloader.\n\t */\n\tvoid addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String firstClass, String... additionalClasses);\n\n\t/**\n\t * Add types that should be loaded (and possibly modified) by the mock\n\t * classloader.\n\t */\n\tvoid addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes);\n\n\t/**\n\t * @return The fully-qualified names to the classes whose static\n\t *         initializers that should be suppressed.\n\t */\n\tString[] getStaticInitializersToSuppress();\n\n\t/**\n\t * @return The fully-qualified names to all types that should be loaded by\n\t *         the mock classloader.\n\t */\n\tString[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/mockpolicies/MockPolicyInterceptionSettings.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.mockpolicies;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.util.Map;\n\n/**\n * Contains interception related settings. PowerMock uses the information stored\n * in this object to intercept method calls and field calls etc and specify a\n * return value or suppression.\n * <p>\n * Since mock policies can be chained subsequent policies can override behavior\n * of a previous policy. To avoid accidental overrides it's recommended\n * <i>add</i> behavior instead of <i>setting</i> behavior since the latter\n * overrides all previous configurations.\n */\npublic interface MockPolicyInterceptionSettings {\n\t/**\n\t * Set which methods to suppress. Note that this overrides all previous\n\t * configurations.\n\t */\n\tvoid setMethodsToSuppress(Method[] methods);\n\n\t/**\n\t * Add methods to suppress upon invocation.\n\t */\n\tvoid addMethodsToSuppress(Method methodToSuppress, Method... additionalMethodsToSuppress);\n\n\t/**\n\t * Add methods to suppress upon invocation.\n\t */\n\tvoid addMethodsToSuppress(Method[] methods);\n\n\t/**\n\t * Set the substitute return values. The substitute return values is a\n\t * key-value map where each key is a method that should be intercepted and\n\t * each value is the new return value for that method when it's intercepted.\n\t * <p>\n\t * Note that this overrides all previous configurations.\n\t */\n\tvoid setMethodsToStub(Map<Method, Object> substituteReturnValues);\n\n\t/**\n\t * Add a method that should be intercepted and return another value (\n\t * {@code returnObject}) (i.e. the method is stubbed).\n\t */\n\tvoid stubMethod(Method method, Object returnObject);\n\n\t/**\n\t * Proxy a method with the given invocation handler. Each call to the method\n\t * will be routed to the invocationHandler instead.\n\t */\n\tvoid proxyMethod(Method method, InvocationHandler invocationHandler);\n\n\t/**\n\t * Get all methods that should be proxied and the invocation handler for\n\t * each method.\n\t */\n\tMap<Method, InvocationHandler> getProxiedMethods();\n\n\t/**\n\t * Set the methods to proxy. The proxies are a key-value map where each key\n\t * is a method that should be intercepted and routed to the invocation\n\t * handler instead.\n\t * <p>\n\t * Note that this overrides all previous configurations.\n\t */\n\tvoid setMethodsToProxy(Map<Method, InvocationHandler> proxies);\n\n\t/**\n\t * Set the substitute return values. The substitute return values is a\n\t * key-value map where each key is a method that should be intercepted and\n\t * each value is the new return value for that method when it's intercepted.\n\t * <p>\n\t * Note that this overrides all previous configurations.\n\t * \n\t * @deprecated Use {@link #stubMethod(Method, Object)} instead.\n\t */\n\t@Deprecated\n\tvoid setSubtituteReturnValues(Map<Method, Object> substituteReturnValues);\n\n\t/**\n\t * Add a method that should be intercepted and return another value (\n\t * {@code returnObject}). The substitute return values is a key-value\n\t * map where each key is a method that should be intercepted and each value\n\t * is the new return value for that method when it's intercepted.\n\t * \n\t * @deprecated Use {@link #stubMethod(Method, Object)} instead.\n\t */\n\t@Deprecated\n\tvoid addSubtituteReturnValue(Method method, Object returnObject);\n\n\t/**\n\t * Set specific fields that should be suppressed upon invocation. Note that\n\t * this overrides all previous configurations.\n\t */\n\tvoid setFieldsSuppress(Field[] fields);\n\n\t/**\n\t * Add specific fields that should be suppressed upon invocation.\n\t */\n\tvoid addFieldToSuppress(Field firstField, Field... additionalFields);\n\n\t/**\n\t * Add specific fields that should be suppressed upon invocation.\n\t */\n\tvoid addFieldToSuppress(Field[] fields);\n\n\t/**\n\t * Set which field types that should be suppressed. Note that this overrides\n\t * all previous configurations.\n\t */\n\tvoid setFieldTypesToSuppress(String[] fieldTypes);\n\n\t/**\n\t * Add field types that should be suppressed.\n\t */\n\tvoid addFieldTypesToSuppress(String firstType, String... additionalFieldTypes);\n\n\t/**\n\t * Add field types that should be suppressed.\n\t */\n\tvoid addFieldTypesToSuppress(String[] fieldTypes);\n\n\t/**\n\t * @return Which methods that should be suppressed/stubbed (i.e. return a\n\t *         default value when invoked).\n\t */\n\tMethod[] getMethodsToSuppress();\n\n\t/**\n\t * Get all substitute return values and also returns an unmodifiable map of\n\t * all method-object pairs the were initialized.\n\t */\n\tMap<Method, Object> getStubbedMethods();\n\n\t/**\n\t * Get all substitute return values and also returns an unmodifiable map of\n\t * all method-object pairs the were initialized.\n\t * \n\t * @deprecated Use {@link #getStubbedMethods()} instead.\n\t */\n\t@Deprecated\n\tMap<Method, Object> getSubstituteReturnValues();\n\n\t/**\n\t * @return Which fields should be suppressed (i.e. will be set to\n\t *         {@code null} or other default values).\n\t */\n\tField[] getFieldsToSuppress();\n\n\t/**\n\t * @return The fully-qualified names to the fields that should be\n\t *         suppressed.\n\t */\n\tString[] getFieldTypesToSuppress();\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyClassLoadingSettingsImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.mockpolicies.impl;\n\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\n\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\n\n/**\n * The default implementation of the {@link MockPolicyClassLoadingSettings}\n * interface.\n */\npublic class MockPolicyClassLoadingSettingsImpl implements MockPolicyClassLoadingSettings {\n\tprivate Set<String> fullyQualifiedNamesOfClassesToLoadByMockClassloader;\n\tprivate Set<String> staticInitializersToSuppress;\n\n\tpublic MockPolicyClassLoadingSettingsImpl() {\n\t\tfullyQualifiedNamesOfClassesToLoadByMockClassloader = new LinkedHashSet<String>();\n\t\tstaticInitializersToSuppress = new LinkedHashSet<String>();\n\t}\n\n\t@Override\n\tpublic String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {\n\t\tif (fullyQualifiedNamesOfClassesToLoadByMockClassloader == null) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn fullyQualifiedNamesOfClassesToLoadByMockClassloader.toArray(new String[fullyQualifiedNamesOfClassesToLoadByMockClassloader.size()]);\n\t}\n\n\t@Override\n\tpublic String[] getStaticInitializersToSuppress() {\n\t\tif (staticInitializersToSuppress == null) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn staticInitializersToSuppress.toArray(new String[staticInitializersToSuppress.size()]);\n\t}\n\n\t@Override\n\tpublic void addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String firstClass, String... additionalClasses) {\n\t\tfullyQualifiedNamesOfClassesToLoadByMockClassloader.add(firstClass);\n\t\taddFullyQualifiedNamesOfClassesToLoadByMockClassloader(additionalClasses);\n\t}\n\n\t@Override\n\tpublic void addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes) {\n\t\tCollections.addAll(fullyQualifiedNamesOfClassesToLoadByMockClassloader, classes);\n\t}\n\n\t@Override\n\tpublic void addStaticInitializersToSuppress(String firstStaticInitializerToSuppress, String... additionalStaticInitializersToSuppress) {\n\t\tstaticInitializersToSuppress.add(firstStaticInitializerToSuppress);\n\t\taddStaticInitializersToSuppress(additionalStaticInitializersToSuppress);\n\t}\n\n\t@Override\n\tpublic void addStaticInitializersToSuppress(String[] staticInitializersToSuppress) {\n\t\tCollections.addAll(this.staticInitializersToSuppress, staticInitializersToSuppress);\n\t}\n\n\t@Override\n\tpublic void setFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes) {\n\t\tfullyQualifiedNamesOfClassesToLoadByMockClassloader.clear();\n\t\taddFullyQualifiedNamesOfClassesToLoadByMockClassloader(classes);\n\t}\n\n\t@Override\n\tpublic void setStaticInitializersToSuppress(String[] staticInitializersToSuppress) {\n\t\tthis.staticInitializersToSuppress.clear();\n\t\taddStaticInitializersToSuppress(staticInitializersToSuppress);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyInterceptionSettingsImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.mockpolicies.impl;\n\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class MockPolicyInterceptionSettingsImpl implements MockPolicyInterceptionSettings {\n\tprivate Set<Field> fieldsToSuppress;\n\tprivate Set<Method> methodsToSuppress;\n\tprivate Map<Method, Object> substituteReturnValues;\n\tprivate Set<String> fieldsTypesToSuppress;\n\tprivate Map<Method, InvocationHandler> proxies;\n\n\tpublic MockPolicyInterceptionSettingsImpl() {\n\t\tfieldsToSuppress = new LinkedHashSet<Field>();\n\t\tmethodsToSuppress = new LinkedHashSet<Method>();\n\t\tsubstituteReturnValues = new HashMap<Method, Object>();\n\t\tproxies = new HashMap<Method, InvocationHandler>();\n\t\tfieldsTypesToSuppress = new LinkedHashSet<String>();\n\t}\n\n\t@Override\n\tpublic void addFieldTypesToSuppress(String firstType, String... additionalFieldTypes) {\n\t\tfieldsTypesToSuppress.add(firstType);\n\t\taddFieldTypesToSuppress(additionalFieldTypes);\n\t}\n\n\t@Override\n\tpublic void addFieldTypesToSuppress(String[] fieldTypes) {\n\t\tCollections.addAll(fieldsTypesToSuppress, fieldTypes);\n\t}\n\n\t@Override\n\tpublic void setFieldTypesToSuppress(String[] fieldTypes) {\n\t\tfieldsTypesToSuppress.clear();\n\t\taddFieldTypesToSuppress(fieldTypes);\n\t}\n\n    @Override\n\tpublic Field[] getFieldsToSuppress() {\n\t\treturn fieldsToSuppress.toArray(new Field[fieldsToSuppress.size()]);\n\t}\n\n    @Override\n\tpublic Method[] getMethodsToSuppress() {\n\t\treturn methodsToSuppress.toArray(new Method[methodsToSuppress.size()]);\n\t}\n\n    @Override\n\tpublic Map<Method, Object> getStubbedMethods() {\n\t\treturn Collections.unmodifiableMap(substituteReturnValues);\n\t}\n\n    @Override\n\tpublic void addFieldToSuppress(Field firstField, Field... fields) {\n\t\tfieldsToSuppress.add(firstField);\n\t\taddFieldToSuppress(fields);\n\t}\n\n    @Override\n\tpublic void addFieldToSuppress(Field[] fields) {\n\t\tCollections.addAll(fieldsToSuppress, fields);\n\t}\n\n    @Override\n\tpublic void addMethodsToSuppress(Method methodToSuppress, Method... additionalMethodsToSuppress) {\n\t\tmethodsToSuppress.add(methodToSuppress);\n\t\taddMethodsToSuppress(additionalMethodsToSuppress);\n\t}\n\n    @Override\n\tpublic void addMethodsToSuppress(Method[] methods) {\n\t\tCollections.addAll(methodsToSuppress, methods);\n\t}\n\n    @Override\n\tpublic void stubMethod(Method method, Object returnObject) {\n\t\tsubstituteReturnValues.put(method, returnObject);\n\t}\n\n    @Override\n\tpublic void setFieldsSuppress(Field[] fields) {\n\t\tfieldsToSuppress.clear();\n\t\taddFieldToSuppress(fields);\n\t}\n\n    @Override\n\tpublic void setMethodsToSuppress(Method[] methods) {\n\t\tmethodsToSuppress.clear();\n\t\taddMethodsToSuppress(methods);\n\t}\n\n    @Override\n\tpublic void setMethodsToStub(Map<Method, Object> substituteReturnValues) {\n\t\tthis.substituteReturnValues = substituteReturnValues;\n\t}\n\n    @Override\n\tpublic String[] getFieldTypesToSuppress() {\n\t\treturn fieldsTypesToSuppress.toArray(new String[fieldsTypesToSuppress.size()]);\n\t}\n\n    @Override\n\tpublic void addSubtituteReturnValue(Method method, Object returnObject) {\n\t\tsubstituteReturnValues.put(method, returnObject);\n\t}\n\n    @Override\n\tpublic void setSubtituteReturnValues(Map<Method, Object> substituteReturnValues) {\n\t\tthis.substituteReturnValues = substituteReturnValues;\n\t}\n\n    @Override\n\tpublic Map<Method, Object> getSubstituteReturnValues() {\n\t\treturn getStubbedMethods();\n\t}\n\n    @Override\n\tpublic Map<Method, InvocationHandler> getProxiedMethods() {\n\t\treturn proxies;\n\t}\n\n    @Override\n\tpublic void proxyMethod(Method method, InvocationHandler invocationHandler) {\n\t\tproxies.put(method, invocationHandler);\n\t}\n\n    @Override\n\tpublic void setMethodsToProxy(Map<Method, InvocationHandler> proxies) {\n\t\tthis.proxies = proxies;\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/mockpolicies/support/LogPolicySupport.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.mockpolicies.support;\n\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Method;\n\n/**\n * A support class for mock policies dealing with logging frameworks.\n */\npublic class LogPolicySupport {\n\t/**\n\t * Get the methods that should be mocked.\n\t * \n\t * @param fullyQualifiedClassName\n\t *            The fully-qualified name to the class that contains the\n\t *            method.\n\t * @param methodName\n\t *            The name of the method that should be mocked.\n\t * @param logFramework\n\t *            The log framework that should be printed if the class\n\t *            {@code fullyQualifiedClassName} cannot be found.\n\t * @return The array of {@link Method}'s that should be mocked.\n\t */\n\tpublic Method[] getLoggerMethods(String fullyQualifiedClassName, String methodName, String logFramework) {\n\t\ttry {\n\t\t\treturn Whitebox.getMethods(getType(fullyQualifiedClassName, logFramework), methodName);\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Get the class type representing the fully-qualified name.\n\t * \n\t * @param name\n\t *            The fully-qualified name of a class to get.\n\t * @param logFramework\n\t *            The log framework that should be printed if the class cannot\n\t *            be found.\n\t * @return The class representing the fully-qualified name.\n\t * @throws Exception\n\t *             If something unexpected goes wrong, for example if the class\n\t *             cannot be found.\n\t */\n\tpublic Class<?> getType(String name, String logFramework) throws Exception {\n\t\tfinal Class<?> loggerType;\n\t\ttry {\n\t\t\tloggerType = Class.forName(name);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\tfinal String message = String.format(\"Cannot find %s in the classpath which the %s policy requires.\", logFramework, getClass()\n\t\t\t\t\t.getSimpleName());\n\t\t\tthrow new RuntimeException(message, e);\n\t\t}\n\t\treturn loggerType;\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/ArrayMerger.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\n/**\n * An array merger concatenates several arrays to one.\n */\npublic interface ArrayMerger {\n\n\t/**\n\t * Merge arrays of a specific type.\n\t */\n\t<T> T[] mergeArrays(Class<T> type, T[]... arraysToMerge);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/IgnorePackagesExtractor.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\nimport java.lang.reflect.AnnotatedElement;\n\npublic interface IgnorePackagesExtractor {\n\t/**\n\t * @return Returns a string-array of all package names if annotation was\n\t *         found.\n\t */\n\tString[] getPackagesToIgnore(AnnotatedElement element);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/Keys.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\n/**\n * Holds various keys that may be put into the MockRepository to store state.\n */\npublic class Keys {\n\n\t/**\n\t * Key that can be used to set or get the current test instance in the mock\n\t * repository.\n\t */\n\tpublic static final String CURRENT_TEST_INSTANCE = \"powermock.test.instance\";\n\n\t/**\n\t * Key that can be used to set or get the current test method in the mock\n\t * repository.\n\t */\n\tpublic static final String CURRENT_TEST_METHOD = \"powermock.test.method\";\n\n\t/**\n\t * Key that can be used to set or get the current test method arguments in\n\t * the mock repository.\n\t */\n\tpublic static final String CURRENT_TEST_METHOD_ARGUMENTS = \"powermock.test.arguments\";\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/MockPolicyInitializer.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\nimport org.powermock.core.classloader.MockClassLoader;\n\n/**\n * A Mock Policy initializer takes care of initializing the behavior defined by\n * the mock policies.\n */\npublic interface MockPolicyInitializer {\n\n\t/**\n\t * Initializes the mock policies for a given class loader. Note that this\n\t * method must <b><i>not</i></b> be called from the class loader (\n\t * {@code classLoader}) that you pass in to this method.\n\t * <p>\n\t * Note that if the class-loader is not an instance of\n\t * {@link MockClassLoader} this method will return silently.\n\t */\n\tvoid initialize(ClassLoader classLoader);\n\n\tboolean needsInitialization();\n\n\t/**\n\t * @return {@code true} if the class with the fully-qualified name of\n\t *         {@code fullyQualifiedClassName} was prepared for testing by\n\t *         this mock policy initializer.\n\t */\n\tboolean isPrepared(String fullyQualifiedClassName);\n\n\t/**\n\t * Re executes the {@link org.powermock.core.classloader.annotations.MockPolicy} of all the policies for a given class\n\t * loader. This method must be called after a call to\n\t * {@link MockPolicyInitializer#initialize(ClassLoader)} on the same class\n\t * loader.\n\t * <p>\n\t * Note that if the class-loader is not an instance of\n\t * {@link MockClassLoader} this method will return silently.\n\t */\n\tvoid refreshPolicies(ClassLoader classLoader);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/PowerMockTestNotifier.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\nimport org.powermock.core.spi.testresult.TestMethodResult;\nimport org.powermock.core.spi.testresult.TestSuiteResult;\n\nimport java.lang.reflect.Method;\n\n/**\n * Implementors of this interface that must provide the ability to notify\n * PowerMock test listeners with the events as specified by the methods declared\n * in this interface.\n */\npublic interface PowerMockTestNotifier {\n    \n    /**\n     * Notifies all listeners with the \"before test method started\" event.\n     *\n     * @param testInstance instance of test\n     * @param testMethod   test method to be executed\n     * @param arguments    arguments of test methods\n     */\n    void notifyBeforeTestMethod(final Object testInstance, final Method testMethod, final Object[] arguments);\n    \n    /**\n     * Notifies all listeners with the \"after test method ended\" event.\n     *\n     * @param testInstance instance of test\n     * @param testMethod   test method to be executed\n     * @param arguments    arguments of test methods\n     * @param testResult   result of running of test\n     */\n    void notifyAfterTestMethod(Object testInstance, Method testMethod, Object[] arguments, TestMethodResult testResult);\n    \n    /**\n     * Notifies all listeners with the \"after test method ended\" event. Uses\n     * some state-store to get the needed state. For this method to work\n     * {@link #notifyBeforeTestMethod(Object, Method, Object[])} must have been\n     * called before this method. Otherwise revert to using the\n     * {@link #notifyAfterTestMethod(Object, Method, Object[], TestMethodResult)}\n     * method.\n     *\n     * @param successful {@code true} if the test was successful,\n     *                   {@code false} otherwise.\n     */\n    void notifyAfterTestMethod(boolean successful);\n    \n    /**\n     * Notifies all listeners with the \"before test suite started\" event.\n     *\n     * @param testClass   class of test suite\n     * @param testMethods test case methods\n     */\n    void notifyBeforeTestSuiteStarted(final Class<?> testClass, final Method[] testMethods);\n    \n    /**\n     * Notifies all listeners with the \"after test suite ended\" event.\n     *\n     * @param testClass  class of test suite\n     * @param methods    test case methods\n     * @param testResult result of running of test\n     */\n    void notifyAfterTestSuiteEnded(Class<?> testClass, Method[] methods, TestSuiteResult testResult);\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/RunnerTestSuiteChunker.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\nimport java.util.List;\n\n/**\n * An interface that should be implemented by classes that performs test suite\n * chunking. Test suite chunking may be performed because certain classes may\n * need to be byte-code manipulated in tests without impacting on other tests.\n * \n * @author Johan Haleby\n */\npublic interface RunnerTestSuiteChunker extends TestSuiteChunker {\n\n\t/**\n\t * Create the test delegators needed for a whole class.\n\t */\n\tvoid createTestDelegators(Class<?> testClass, List<TestChunk> chunks) throws Exception;\n\n\n\t/**\n\t * Get the number of total tests defined in the suite (the sum of all tests\n\t * defined in all chunks for this suite).\n\t * \n\t * @return The number of tests in this suite.\n\t */\n\tint getTestCount();\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/TestChunk.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\nimport java.lang.reflect.Method;\nimport java.util.List;\n\n/**\n * A test chunk consists of a list of methods that should be executed by a\n * particular classloader.\n * */\npublic interface TestChunk {\n\n\tClassLoader getClassLoader();\n\n\tList<Method> getTestMethodsToBeExecutedByThisClassloader();\n\n\tboolean isMethodToBeExecutedByThisClassloader(Method method);\n}"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/TestClassesExtractor.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils;\n\nimport java.lang.reflect.AnnotatedElement;\n\npublic interface TestClassesExtractor {\n\t/**\n\t * @return Returns {@code null} if the element was not annotated, an\n\t *         empty String[] if it is annotated but contains no classes, or a\n\t *         string-array of all class names if interest.\n\t */\n\tString[] getTestClasses(AnnotatedElement element);\n\n\tboolean isPrepared(AnnotatedElement element, String fullyQualifiedClassName);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/TestSuiteChunker.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.tests.utils;\n\nimport java.lang.reflect.Method;\nimport java.util.List;\n\n/**\n *\n */\npublic interface TestSuiteChunker {\n\n\n    /**\n     * Get the number of chunks defined in this suite.\n     *\n     * @return The number of chunks defined in the correct suite.\n     */\n    int getChunkSize();\n\n    /**\n     * Get all chunk entries.\n     *\n     * @return An set of entries that contains a list of methods contained in\n     * the chunk and the class loader that loaded these methods.\n     */\n    List<TestChunk> getTestChunks();\n\n    /**\n     * Get all chunk entries for a specific class.\n     *\n     * @param testClass The class whose chunk entries to get.\n     * @return An set of entries that contains a list of methods contained in\n     * the chunk for the specific test class and the class loader that\n     * loaded these methods.\n     */\n    List<TestChunk> getTestChunksEntries(Class<?> testClass);\n\n    /**\n     * Get TestChunk for the given method.\n     *\n     * @param method - method for which test chunk should be found.\n     * @return TestChunk for this method.\n     */\n    TestChunk getTestChunk(Method method);\n\n    /**\n     * Should reflect whether or not this method is eligible for testing.\n     *\n     * @param testClass           The class that defines the method.\n     * @param potentialTestMethod The method to inspect whether it should be executed in the\n     *                            test suite or not.\n     * @return {@code true} if the method is a test method and should be\n     * executed, {@code false} otherwise.\n     */\n    boolean shouldExecuteTestForMethod(Class<?> testClass, Method potentialTestMethod);\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractCommonTestSuiteChunkerImpl.java",
    "content": "package org.powermock.tests.utils.impl;\n\nimport org.powermock.core.classloader.MockClassLoaderFactory;\nimport org.powermock.core.classloader.annotations.PrepareEverythingForTest;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.TestClassTransformerBuilder;\nimport org.powermock.tests.utils.TestChunk;\nimport org.powermock.tests.utils.TestSuiteChunker;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic abstract class AbstractCommonTestSuiteChunkerImpl implements TestSuiteChunker {\n    \n    protected static final int NOT_INITIALIZED = -1;\n    \n    static final int DEFAULT_TEST_LISTENERS_SIZE = 1;\n    static final int INTERNAL_INDEX_NOT_FOUND = NOT_INITIALIZED;\n\n    /*\n    * Maps between a specific class and a map of test methods loaded by a\n    * specific mock class loader.\n    */\n    private final List<TestCaseEntry> internalSuites = new LinkedList<TestCaseEntry>();\n    /*\n     * Maps the list of test indexes that is assigned to a specific test suite\n     * index.\n     */\n    final LinkedHashMap<Integer, List<Integer>> testAtDelegateMapper = new LinkedHashMap<Integer, List<Integer>>();\n    final Class<?>[] testClasses;\n    \n    private int currentTestIndex = NOT_INITIALIZED;\n\n\n    protected AbstractCommonTestSuiteChunkerImpl(Class<?> testClass) throws Exception {\n        this(new Class[]{testClass});\n    }\n\n    AbstractCommonTestSuiteChunkerImpl(Class<?>... testClasses) throws Exception {\n        this.testClasses = testClasses;\n        for (Class<?> clazz : testClasses) {\n            chunkClass(clazz);\n        }\n    }\n\n    @Override\n    public int getChunkSize() {\n        return getTestChunks().size();\n    }\n\n    public List<TestChunk> getTestChunks() {\n        List<TestChunk> allChunks = new LinkedList<TestChunk>();\n        for (TestCaseEntry entry : internalSuites) {\n            allChunks.addAll(entry.getTestChunks());\n        }\n        return allChunks;\n    }\n\n    public List<TestChunk> getTestChunksEntries(Class<?> testClass) {\n        for (TestCaseEntry entry : internalSuites) {\n            if (entry.getTestClass().equals(testClass)) {\n                return entry.getTestChunks();\n            }\n        }\n        return null;\n    }\n\n    public TestChunk getTestChunk(Method method) {\n        for (TestChunk testChunk : getTestChunks()) {\n            if (testChunk.isMethodToBeExecutedByThisClassloader(method)) {\n                return testChunk;\n            }\n        }\n        return null;\n    }\n    \n    private void chunkClass(final Class<?> testClass) throws Exception {\n\n        List<Method> testMethodsForOtherClassLoaders = new ArrayList<Method>();\n        \n        final ClassLoader defaultMockLoader = createDefaultMockLoader(testClass, testMethodsForOtherClassLoaders);\n    \n        List<Method> currentClassloaderMethods = new LinkedList<Method>();\n        TestChunk defaultTestChunk = new TestChunkImpl(defaultMockLoader, currentClassloaderMethods);\n        \n        // Put the first suite in the map of internal suites.\n        List<TestChunk> testChunks = new LinkedList<TestChunk>();\n        testChunks.add(defaultTestChunk);\n        \n        internalSuites.add(new TestCaseEntry(testClass, testChunks));\n        initEntries(internalSuites);\n        \n        if (!currentClassloaderMethods.isEmpty()) {\n            List<TestChunk> allTestChunks = internalSuites.get(0).getTestChunks();\n            for (TestChunk chunk : allTestChunks.subList(1, allTestChunks.size())) {\n                testMethodsForOtherClassLoaders.addAll(chunk.getTestMethodsToBeExecutedByThisClassloader());\n            }\n        } else if (2 <= internalSuites.size()\n                           || 1 == internalSuites.size()\n                                      && 2 <= internalSuites.get(0).getTestChunks().size()) {\n            /*\n             * If we don't have any test that should be executed by the default\n             * class loader remove it to avoid duplicate test print outs.\n             */\n            internalSuites.get(0).getTestChunks().remove(0);\n        }\n        //else{ /*Delegation-runner maybe doesn't use test-method annotations!*/ }\n    }\n    \n    private ClassLoader createDefaultMockLoader(final Class<?> testClass, final Collection<Method> testMethodsForOtherClassLoaders) {\n        final MockTransformer extraMockTransformer;\n        if (null == testMethodAnnotation()) {\n            extraMockTransformer = null;\n        } else {\n            extraMockTransformer = TestClassTransformerBuilder\n                                       .forTestClass(testClass)\n                                       .removesTestMethodAnnotation(testMethodAnnotation())\n                                       .fromMethods(testMethodsForOtherClassLoaders);\n        }\n        return new MockClassLoaderFactory(testClass).createForClass(extraMockTransformer);\n    }\n    \n    private void putMethodToChunk(TestCaseEntry testCaseEntry, Class<?> testClass, Method method) {\n        if (shouldExecuteTestForMethod(testClass, method)) {\n            currentTestIndex++;\n            if (hasChunkAnnotation(method)) {\n                LinkedList<Method> methodsInThisChunk = new LinkedList<Method>();\n                methodsInThisChunk.add(method);\n                \n                final ClassLoader mockClassloader = createClassLoaderForMethod(testClass, method);\n                \n                final TestChunkImpl chunk = new TestChunkImpl(mockClassloader, methodsInThisChunk);\n                testCaseEntry.getTestChunks().add(chunk);\n                updatedIndexes();\n            } else {\n                testCaseEntry.getTestChunks().get(0).getTestMethodsToBeExecutedByThisClassloader().add(method);\n                // currentClassloaderMethods.add(method);\n                final int currentDelegateIndex = internalSuites.size() - 1;\n                /*\n                 * Add this test index to the main junit runner\n                 * delegator.\n                 */\n                List<Integer> testList = testAtDelegateMapper.get(currentDelegateIndex);\n                if (testList == null) {\n                    testList = new LinkedList<Integer>();\n                    testAtDelegateMapper.put(currentDelegateIndex, testList);\n                }\n                \n                testList.add(currentTestIndex);\n            }\n        }\n    }\n    \n    private ClassLoader createClassLoaderForMethod(final Class<?> testClass, final Method method) {\n        \n        final MockTransformer extraMockTransformer;\n        if (null == testMethodAnnotation()) {\n            extraMockTransformer = null;\n        } else {\n            extraMockTransformer = TestClassTransformerBuilder.forTestClass(testClass)\n                                                              .bytecodeFrameworkClue(method)\n                                                              .removesTestMethodAnnotation(testMethodAnnotation())\n                                                              .fromAllMethodsExcept(method);\n        }\n        \n        final MockClassLoaderFactory classLoaderFactory = new MockClassLoaderFactory(testClass);\n        return classLoaderFactory.createForMethod(method, extraMockTransformer);\n    }\n    \n    protected Class<? extends Annotation> testMethodAnnotation() {\n        return null;\n    }\n    \n    private void initEntries(List<TestCaseEntry> entries) {\n        for (TestCaseEntry testCaseEntry : entries) {\n            final Class<?> testClass = testCaseEntry.getTestClass();\n            findMethods(testCaseEntry, testClass);\n        }\n    }\n    \n    private void findMethods(TestCaseEntry testCaseEntry, Class<?> testClass) {\n        Method[] allMethods = testClass.getMethods();\n        for (Method method : allMethods) {\n            putMethodToChunk(testCaseEntry, testClass, method);\n        }\n        testClass = testClass.getSuperclass();\n        if (!Object.class.equals(testClass)) {\n            findMethods(testCaseEntry, testClass);\n        }\n    }\n\n    private boolean hasChunkAnnotation(Method method) {\n        return method.isAnnotationPresent(PrepareForTest.class) || method.isAnnotationPresent(SuppressStaticInitializationFor.class)\n                       || method.isAnnotationPresent(PrepareOnlyThisForTest.class) || method.isAnnotationPresent(PrepareEverythingForTest.class);\n    }\n\n    private void updatedIndexes() {\n        final List<Integer> testIndexesForThisClassloader = new LinkedList<Integer>();\n        testIndexesForThisClassloader.add(currentTestIndex);\n        testAtDelegateMapper.put(internalSuites.size(), testIndexesForThisClassloader);\n    }\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestClassExtractor.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.tests.utils.TestClassesExtractor;\n\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * Base class for all test class extractors.\n */\npublic abstract class AbstractTestClassExtractor implements TestClassesExtractor {\n\n    protected final boolean includeMethods;\n\n    protected AbstractTestClassExtractor(){\n        this(false);\n    }\n\n    protected AbstractTestClassExtractor(boolean includeMethods) {this.includeMethods = includeMethods;}\n\n    /**\n     * If {@code element} is a class this method traverses the hierarchy\n     * and extracts classes that should be prepared for test in all super\n     * classes.\n     */\n    @Override\n    public final String[] getTestClasses(AnnotatedElement element) {\n        final Set<String> classesToPrepareForTest = new HashSet<String>();\n        if (element instanceof Class<?>) {\n            extractClassesFromTestClass((Class<?>) element, classesToPrepareForTest);\n        } else {\n            extractClassesAndAddThemToList(element, classesToPrepareForTest);\n        }\n        return classesToPrepareForTest.toArray(new String[classesToPrepareForTest.size()]);\n    }\n\n    private void extractClassesFromTestClass(final Class<?> element, Set<String> classesToPrepareForTest) {\n        Class<?> classToInvestigate = element;\n        while (classToInvestigate != null && !classToInvestigate.equals(Object.class)) {\n            extractClassesAndAddThemToList(classToInvestigate, classesToPrepareForTest);\n            if (includeMethods) {\n                classesToPrepareForTest.addAll(lookOverMethods(classToInvestigate));\n            }\n            classToInvestigate = classToInvestigate.getSuperclass();\n        }\n    }\n\n    private Collection<String> lookOverMethods(Class<?> classToInvestigate) {\n        Set<String> classesToPrepareForTest = new HashSet<String>();\n        for (Method method : classToInvestigate.getMethods()) {\n            extractClassesAndAddThemToList(method, classesToPrepareForTest);\n        }\n        return classesToPrepareForTest;\n    }\n\n    private void extractClassesAndAddThemToList(AnnotatedElement elementToExtractClassFrom, final Set<String> classesToPrepareForTest) {\n        final String[] classesToModify = getClassesToModify(elementToExtractClassFrom);\n        if (classesToModify != null) {\n            Collections.addAll(classesToPrepareForTest, classesToModify);\n        }\n    }\n\n    /**\n     * Get the fully qualified names for classes that must should be modified\n     * for this {@code element}.\n     *\n     * @param element The element that may contain info regarding which classes that\n     *                must be modified by PowerMock.\n     * @return An array of fully-qualified names to classes that must be\n     * modified by PowerMock for the specific {@code element}.\n     */\n    protected abstract String[] getClassesToModify(AnnotatedElement element);\n\n    @Override\n    public boolean isPrepared(AnnotatedElement element, String fullyQualifiedClassName) {\n        if (fullyQualifiedClassName == null) {\n            throw new IllegalArgumentException(\"fullyQualifiedClassName cannot be null.\");\n        }\n        final String[] testClasses = getTestClasses(element);\n        for (String className : testClasses) {\n            if (className.equals(fullyQualifiedClassName)) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestSuiteChunkerImpl.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.RunnerTestSuiteChunker;\nimport org.powermock.tests.utils.TestChunk;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\n/**\n * Abstract base class for test suite chunking, i.e. a suite is chunked into\n * several smaller pieces which are ran with different classloaders. A chunk is\n * defined by the {@link PrepareForTest} annotation and whichever test-method\n * annotation the actual implementation-class specifies by overriding the\n * method {@link #testMethodAnnotation()}. This to make sure that you\n * can byte-code manipulate classes in tests without impacting on other tests.\n * \n */\npublic abstract class AbstractTestSuiteChunkerImpl<T> extends AbstractCommonTestSuiteChunkerImpl implements RunnerTestSuiteChunker {\n\n    /*\n     * The classes listed in this set has been chunked and its delegates has\n     * been created.\n     */\n    protected final Set<Class<?>> delegatesCreatedForTheseClasses = new LinkedHashSet<Class<?>>();\n\n    // A list of junit delegates.\n    protected final List<T> delegates = new ArrayList<T>();\n\n    protected volatile int testCount = NOT_INITIALIZED;\n\n    protected AbstractTestSuiteChunkerImpl(Class<?> testClass) throws Exception {\n        super(testClass);\n    }\n\n    protected AbstractTestSuiteChunkerImpl(Class<?>... testClasses) throws Exception {\n        super(testClasses);\n    }\n\n    protected Object getPowerMockTestListenersLoadedByASpecificClassLoader(Class<?> clazz, ClassLoader classLoader) {\n        try {\n            int defaultListenerSize = DEFAULT_TEST_LISTENERS_SIZE;\n            Class<?> annotationEnablerClass = null;\n            try {\n                annotationEnablerClass = Class.forName(\"org.powermock.api.extension.listener.AnnotationEnabler\", false, classLoader);\n            } catch (ClassNotFoundException e) {\n                // Annotation enabler wasn't found in class path\n                defaultListenerSize = 0;\n            }\n\n            final Class<?> powerMockTestListenerType = Class.forName(PowerMockTestListener.class.getName(), false, classLoader);\n            Object testListeners = null;\n            if (clazz.isAnnotationPresent(PowerMockListener.class)) {\n                PowerMockListener annotation = clazz.getAnnotation(PowerMockListener.class);\n                final Class<? extends PowerMockTestListener>[] powerMockTestListeners = annotation.value();\n                if (powerMockTestListeners.length > 0) {\n                    testListeners = Array.newInstance(powerMockTestListenerType, powerMockTestListeners.length + defaultListenerSize);\n                    for (int i = 0; i < powerMockTestListeners.length; i++) {\n                        String testListenerClassName = powerMockTestListeners[i].getName();\n                        final Class<?> listenerTypeLoadedByClassLoader = Class.forName(testListenerClassName, false, classLoader);\n                        Array.set(testListeners, i, Whitebox.newInstance(listenerTypeLoadedByClassLoader));\n                    }\n                }\n            } else {\n                testListeners = Array.newInstance(powerMockTestListenerType, defaultListenerSize);\n            }\n\n            // Add default annotation enabler listener\n            if (annotationEnablerClass != null) {\n                Array.set(testListeners, Array.getLength(testListeners) - 1, Whitebox.newInstance(annotationEnablerClass));\n            }\n\n            return testListeners;\n        } catch (ClassNotFoundException e) {\n            throw new IllegalStateException(\"PowerMock internal error: Failed to load class.\", e);\n        }\n    }\n\n    public final void createTestDelegators(Class<?> testClass, List<TestChunk> chunks) throws Exception {\n        for (TestChunk chunk : chunks) {\n            ClassLoader classLoader = chunk.getClassLoader();\n            List<Method> methodsToTest = chunk.getTestMethodsToBeExecutedByThisClassloader();\n            T runnerDelegator = createDelegatorFromClassloader(classLoader, testClass, methodsToTest);\n            delegates.add(runnerDelegator);\n        }\n        delegatesCreatedForTheseClasses.add(testClass);\n    }\n\n    protected abstract T createDelegatorFromClassloader(ClassLoader classLoader, Class<?> testClass, final List<Method> methodsToTest)\n            throws Exception;\n\n    /**\n     * Get the internal test index for a junit runner delegate based on the\n     * \"real\" original test index. For example, the test may need to run a\n     * single test, for example the test with index 3. However since PowerMock\n     * may have chunked the test suite to use many classloaders and junit\n     * delegators the index (3) must be mapped to an internal representation for\n     * the specific junit runner delegate. This is what this method does. I.e.\n     * it will iterate through all junit runner delegates and see if they\n     * contain the test with index 3, in the internal index of this test\n     * delegator is returned.\n     * \n     * @param originalTestIndex\n     *            The original test index as seen by the test runner.\n     * @return The internal test index as seen by PowerMock or {@code -1}\n     *         if no index was found.\n     * \n     */\n    public int getInternalTestIndex(int originalTestIndex) {\n        Set<Entry<Integer, List<Integer>>> delegatorEntrySet = testAtDelegateMapper.entrySet();\n        for (Entry<Integer, List<Integer>> entry : delegatorEntrySet) {\n            final List<Integer> testIndexesForThisDelegate = entry.getValue();\n            final int internalIndex = testIndexesForThisDelegate.indexOf(originalTestIndex);\n            if (internalIndex != INTERNAL_INDEX_NOT_FOUND) {\n                return internalIndex;\n            }\n        }\n        return INTERNAL_INDEX_NOT_FOUND;\n    }\n\n    /**\n     * Get the junit runner delegate that handles the test at index\n     * {@code testIndex}. Throws a {@link RuntimeException} if a delegator\n     * is not found for the specific test index.\n     * \n     * @param testIndex\n     *            The test index that a delegator should hold.\n     * @return The index for of the junit runner delegate as seen by JTestRack.\n     */\n    public int getDelegatorIndex(int testIndex) {\n        int delegatorIndex = -1;\n        Set<Entry<Integer, List<Integer>>> entrySet = testAtDelegateMapper.entrySet();\n        for (Entry<Integer, List<Integer>> entry : entrySet) {\n            // If the delegator contains the test case, return the index of the\n            // delegator.\n            if (entry.getValue().contains(testIndex)) {\n                delegatorIndex = entry.getKey();\n                break;\n            }\n        }\n\n        if (delegatorIndex == -1) {\n            throw new RuntimeException(\"Internal error: Failed to find the delegator index.\");\n        }\n        return delegatorIndex;\n    }\n\n    protected Class<?>[] getTestClasses() {\n        return testClasses;\n    }\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/ArrayMergerImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.tests.utils.ArrayMerger;\n\nimport java.lang.reflect.Array;\n\n/**\n * The default implementation of the {@link ArrayMerger} interface.\n */\npublic class ArrayMergerImpl implements ArrayMerger {\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic <T> T[] mergeArrays(Class<T> type, T[]... arraysToMerge) {\n\t\tif (arraysToMerge == null || arraysToMerge.length == 0) {\n\t\t\treturn (T[]) Array.newInstance(type, 0);\n\t\t}\n\n\t\tint size = 0;\n\t\tfor (T[] array : arraysToMerge) {\n\t\t\tif (array != null) {\n\t\t\t\tsize += array.length;\n\t\t\t}\n\t\t}\n\n\t\tfinal T[] finalArray = (T[]) Array.newInstance(type, size);\n\n\t\tint lastIndex = 0;\n\t\tfor (final T[] currentArray : arraysToMerge) {\n\t\t\tif (currentArray != null) {\n\t\t\t\tfinal int currentArrayLength = currentArray.length;\n\t\t\t\tSystem.arraycopy(currentArray, 0, finalArray, lastIndex, currentArrayLength);\n\t\t\t\tlastIndex += currentArrayLength;\n\t\t\t}\n\t\t}\n\n\t\treturn finalArray;\n\t}\n\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/MockPolicyInitializerImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.classloader.MockClassLoaderConfiguration;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.mockpolicies.impl.MockPolicyClassLoadingSettingsImpl;\nimport org.powermock.mockpolicies.impl.MockPolicyInterceptionSettingsImpl;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.MockPolicyInitializer;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.Arrays;\nimport java.util.Map.Entry;\n\n/**\n * The default implementation of the {@link MockPolicyInitializer} interface for\n * mock policies.\n */\npublic class MockPolicyInitializerImpl implements MockPolicyInitializer {\n    \n    private final PowerMockPolicy[] mockPolicies;\n    private final Class<? extends PowerMockPolicy>[] mockPolicyTypes;\n    private final Class<?> testClass;\n    \n    public MockPolicyInitializerImpl(Class<? extends PowerMockPolicy>[] mockPolicies) {\n        this(mockPolicies, false);\n    }\n    \n    public MockPolicyInitializerImpl(Class<?> testClass) {\n        this(getMockPolicies(testClass), testClass, false);\n    }\n    \n    private MockPolicyInitializerImpl(Class<? extends PowerMockPolicy>[] mockPolicies, boolean internal) {\n        this(mockPolicies, null, internal);\n    }\n    \n    private MockPolicyInitializerImpl(Class<? extends PowerMockPolicy>[] mockPolicies, Class<?> testClass,\n                                      boolean internal) {\n        this.testClass = testClass;\n        if (internal) {\n            mockPolicyTypes = null;\n        } else {\n            mockPolicyTypes = mockPolicies;\n        }\n        if (mockPolicies == null) {\n            this.mockPolicies = new PowerMockPolicy[0];\n        } else {\n            this.mockPolicies = new PowerMockPolicy[mockPolicies.length];\n            for (int i = 0; i < mockPolicies.length; i++) {\n                this.mockPolicies[i] = Whitebox.newInstance(mockPolicies[i]);\n            }\n        }\n    }\n    \n    /**\n     * Get the mock policies from a test-class.\n     */\n    @SuppressWarnings(\"unchecked\")\n    private static Class<? extends PowerMockPolicy>[] getMockPolicies(Class<?> testClass) {\n        Class<? extends PowerMockPolicy>[] powerMockPolicies = new Class[0];\n        if (testClass.isAnnotationPresent(MockPolicy.class)) {\n            MockPolicy annotation = testClass.getAnnotation(MockPolicy.class);\n            powerMockPolicies = annotation.value();\n        }\n        return powerMockPolicies;\n    }\n    \n    @Override\n    public boolean isPrepared(String fullyQualifiedClassName) {\n        MockPolicyClassLoadingSettings settings = getClassLoadingSettings();\n        final boolean foundInSuppressStaticInitializer = Arrays.binarySearch(settings.getStaticInitializersToSuppress(), fullyQualifiedClassName) < 0;\n        final boolean foundClassesLoadedByMockClassloader = Arrays.binarySearch(settings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader(),\n                                                                                fullyQualifiedClassName) < 0;\n        return foundInSuppressStaticInitializer || foundClassesLoadedByMockClassloader;\n    }\n    \n    @Override\n    public boolean needsInitialization() {\n        MockPolicyClassLoadingSettings settings = getClassLoadingSettings();\n        return settings.getStaticInitializersToSuppress().length > 0 || settings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader().length > 0;\n    }\n    \n    @Override\n    public void initialize(ClassLoader classLoader) {\n        if (classLoader instanceof MockClassLoader) {\n            initialize(((MockClassLoader) classLoader));\n        }\n    }\n    \n    private void initialize(MockClassLoader classLoader) {\n        if (mockPolicies.length > 0) {\n            updateClassLoaderConfiguration(classLoader.getConfiguration());\n            invokeInitializeInterceptionSettingsFromClassLoader(classLoader);\n        }\n    }\n    \n    private void updateClassLoaderConfiguration(MockClassLoaderConfiguration configuration) {\n        \n        MockPolicyClassLoadingSettings classLoadingSettings = getClassLoadingSettings();\n        String[] fullyQualifiedNamesOfClassesToLoadByMockClassloader = classLoadingSettings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader();\n        configuration.addClassesToModify(fullyQualifiedNamesOfClassesToLoadByMockClassloader);\n        \n        if (testClass == null) {\n            throw new IllegalStateException(\"Internal error: testClass should never be null when calling initialize on a mock policy\");\n        }\n        \n        configuration.addClassesToModify(testClass.getName());\n        Class<?>[] classes = testClass.getDeclaredClasses();\n        for (Class<?> clazz : classes) {\n            configuration.addClassesToModify(clazz.getName());\n        }\n        Class<?>[] declaredClasses = testClass.getClasses();\n        for (Class<?> clazz : declaredClasses) {\n            configuration.addClassesToModify(clazz.getName());\n        }\n        \n        for (String string : classLoadingSettings.getStaticInitializersToSuppress()) {\n            configuration.addClassesToModify(string);\n            MockRepository.addSuppressStaticInitializer(string);\n        }\n    }\n    \n    @Override\n    public void refreshPolicies(ClassLoader classLoader) {\n        if (classLoader instanceof MockClassLoader) {\n            invokeInitializeInterceptionSettingsFromClassLoader((MockClassLoader) classLoader);\n        }\n    }\n    \n    private void invokeInitializeInterceptionSettingsFromClassLoader(MockClassLoader classLoader) {\n        try {\n            final int sizeOfPolicies = mockPolicyTypes.length;\n            Object mockPolicies = Array.newInstance(Class.class, sizeOfPolicies);\n            for (int i = 0; i < sizeOfPolicies; i++) {\n                final Class<?> policyLoadedByClassLoader = Class.forName(mockPolicyTypes[i].getName(), false, classLoader);\n                Array.set(mockPolicies, i, policyLoadedByClassLoader);\n            }\n            final Class<?> thisTypeLoadedByMockClassLoader = Class.forName(this.getClass()\n                                                                               .getName(), false, classLoader);\n            Object mockPolicyHandler = Whitebox.invokeConstructor(thisTypeLoadedByMockClassLoader, mockPolicies, true);\n            Whitebox.invokeMethod(mockPolicyHandler, \"initializeInterceptionSettings\");\n        } catch (InvocationTargetException e) {\n            final Throwable targetException = e.getTargetException();\n            if (targetException instanceof RuntimeException) {\n                throw (RuntimeException) targetException;\n            } else if (targetException instanceof Error) {\n                throw (Error) targetException;\n            } else {\n                throw new RuntimeException(e);\n            }\n        } catch (RuntimeException e) {\n            throw e;\n        } catch (Exception e) {\n            throw new IllegalStateException(\"PowerMock internal error: Failed to load class.\", e);\n        }\n    }\n    \n    /*\n     * This method IS used, but it's invoked using reflection from the\n     * invokeInitializeInterceptionSettingsFromClassLoader method.\n     */\n    @SuppressWarnings(\"unused\")\n    private void initializeInterceptionSettings() {\n        MockPolicyInterceptionSettings interceptionSettings = getInterceptionSettings();\n        \n        for (Method method : interceptionSettings.getMethodsToSuppress()) {\n            MockRepository.addMethodToSuppress(method);\n        }\n        \n        for (Entry<Method, InvocationHandler> entry : interceptionSettings.getProxiedMethods().entrySet()) {\n            MockRepository.putMethodProxy(entry.getKey(), entry.getValue());\n        }\n        \n        for (Entry<Method, Object> entry : interceptionSettings.getStubbedMethods().entrySet()) {\n            final Method method = entry.getKey();\n            final Object className = entry.getValue();\n            MockRepository.putMethodToStub(method, className);\n        }\n        \n        for (Field field : interceptionSettings.getFieldsToSuppress()) {\n            MockRepository.addFieldToSuppress(field);\n        }\n        \n        for (String type : interceptionSettings.getFieldTypesToSuppress()) {\n            MockRepository.addFieldTypeToSuppress(type);\n        }\n    }\n    \n    private MockPolicyInterceptionSettings getInterceptionSettings() {\n        MockPolicyInterceptionSettings settings = new MockPolicyInterceptionSettingsImpl();\n        for (PowerMockPolicy mockPolicy : mockPolicies) {\n            mockPolicy.applyInterceptionPolicy(settings);\n        }\n        return settings;\n    }\n    \n    private MockPolicyClassLoadingSettings getClassLoadingSettings() {\n        MockPolicyClassLoadingSettings settings = new MockPolicyClassLoadingSettingsImpl();\n        for (PowerMockPolicy mockPolicy : mockPolicies) {\n            mockPolicy.applyClassLoadingPolicy(settings);\n        }\n        return settings;\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.configuration.GlobalConfiguration;\nimport org.powermock.configuration.PowerMockConfiguration;\nimport org.powermock.core.classloader.annotations.PowerMockIgnore;\nimport org.powermock.tests.utils.IgnorePackagesExtractor;\n\nimport java.lang.reflect.AnnotatedElement;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class PowerMockIgnorePackagesExtractorImpl implements IgnorePackagesExtractor {\n    \n    @Override\n    public String[] getPackagesToIgnore(AnnotatedElement element) {\n    \n        PowerMockIgnore annotation = element.getAnnotation(PowerMockIgnore.class);\n        boolean useGlobal = true;\n        \n        if (annotation != null){\n            useGlobal = annotation.globalIgnore();\n        }\n        \n        Set<String> ignoredPackages = new HashSet<String>();\n        useGlobal &= extractPackageToIgnore(element, ignoredPackages);\n        \n        final String[] packageToIgnore = ignoredPackages.toArray(new String[ignoredPackages.size()]);\n        if (useGlobal) {\n            return getPackageToIgnoreWithGlobal(packageToIgnore);\n        } else {\n            return packageToIgnore;\n        }\n    }\n    \n    private String[] getPackageToIgnoreWithGlobal(final String[] packageToIgnore) {\n        String[] globalIgnore = getGlobalIgnore();\n        \n        final String[] allPackageToIgnore;\n        if (globalIgnore != null) {\n            allPackageToIgnore = addGlobalIgnore(packageToIgnore, globalIgnore);\n        } else {\n            allPackageToIgnore = packageToIgnore;\n        }\n        \n        return allPackageToIgnore;\n    }\n    \n    private String[] getGlobalIgnore() {\n        final PowerMockConfiguration powerMockConfiguration = GlobalConfiguration.powerMockConfiguration();\n        return powerMockConfiguration.getGlobalIgnore();\n    }\n    \n    private boolean extractPackageToIgnore(final AnnotatedElement element, final Set<String> ignoredPackages) {\n        boolean useGlobalFromAnnotation = addValueFromAnnotation(element, ignoredPackages);\n        boolean useGlobalFromSuperclass = addValuesFromSuperclass((Class<?>) element, ignoredPackages);\n        \n        return useGlobalFromAnnotation & useGlobalFromSuperclass;\n    }\n    \n    private boolean  addValuesFromSuperclass(final Class<?> element, final Set<String> ignoredPackages) {\n        final Collection<Class<?>> superclasses = new ArrayList<Class<?>>();\n        Collections.addAll(superclasses, element.getSuperclass());\n        Collections.addAll(superclasses, element.getInterfaces());\n        \n        boolean useGlobalIgnore = true;\n        \n        for (Class<?> superclass : superclasses) {\n            if (superclass != null && !superclass.equals(Object.class)) {\n                useGlobalIgnore &= extractPackageToIgnore(superclass, ignoredPackages);\n            }\n        }\n        \n        return useGlobalIgnore;\n    }\n    \n    private boolean addValueFromAnnotation(final AnnotatedElement element, final Set<String> ignoredPackages) {\n        PowerMockIgnore annotation = element.getAnnotation(PowerMockIgnore.class);\n        \n        if (annotation != null) {\n            String[] ignores = annotation.value();\n            Collections.addAll(ignoredPackages, ignores);\n            return annotation.globalIgnore();\n        }\n        \n        return true;\n    }\n    \n    private String[] addGlobalIgnore(final String[] packageToIgnore, final String[] globalIgnore) {\n        final String[] allPackageToIgnore;\n        \n        allPackageToIgnore = new String[globalIgnore.length + packageToIgnore.length];\n        \n        System.arraycopy(globalIgnore, 0, allPackageToIgnore, 0, globalIgnore.length);\n        System.arraycopy(packageToIgnore, 0, allPackageToIgnore, globalIgnore.length, packageToIgnore.length);\n        \n        return allPackageToIgnore;\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockTestNotifierImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.core.spi.testresult.Result;\nimport org.powermock.core.spi.testresult.TestMethodResult;\nimport org.powermock.core.spi.testresult.TestSuiteResult;\nimport org.powermock.core.spi.testresult.impl.TestMethodResultImpl;\nimport org.powermock.tests.utils.Keys;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\n\nimport java.lang.reflect.Method;\n\n/**\n * Utility class that may be used by PowerMock test runners to notify listeners.\n * Uses the {@link MockRepository} to set and get state.\n */\npublic class PowerMockTestNotifierImpl implements PowerMockTestNotifier {\n\n\tprivate static final String ERROR_MESSAGE_TEMPLATE = \"Invoking the %s method on PowerMock test listener %s failed.\";\n\n\tprivate final PowerMockTestListener[] powerMockTestListeners;\n\n\t/**\n\t * Create a new instance with the following parameters.\n\t * \n\t * @param powerMockTestListeners\n\t *            The PowerMock listeners that will be notified.\n\t */\n\tpublic PowerMockTestNotifierImpl(PowerMockTestListener[] powerMockTestListeners) {\n\t\tif (powerMockTestListeners == null) {\n\t\t\tthis.powerMockTestListeners = new PowerMockTestListener[0];\n\t\t} else {\n\t\t\tthis.powerMockTestListeners = powerMockTestListeners;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void notifyAfterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) {\n\t\tfor (final PowerMockTestListener testListener : powerMockTestListeners) {\n\t\t\ttry {\n\t\t\t\ttestListener.afterTestMethod(testInstance, method, arguments, testResult);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, \"afterTestMethod\", testListener), e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void notifyAfterTestSuiteEnded(Class<?> testClass, Method[] methods, TestSuiteResult testResult) {\n\t\tfor (PowerMockTestListener powerMockTestListener : powerMockTestListeners) {\n\t\t\ttry {\n\t\t\t\tpowerMockTestListener.afterTestSuiteEnded(testClass, methods, testResult);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, \"afterTestSuiteEnded\", powerMockTestListener), e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void notifyBeforeTestMethod(Object testInstance, Method testMethod, Object[] arguments) {\n\t\tMockRepository.putAdditionalState(Keys.CURRENT_TEST_INSTANCE, testInstance);\n\t\tMockRepository.putAdditionalState(Keys.CURRENT_TEST_METHOD, testMethod);\n\t\tMockRepository.putAdditionalState(Keys.CURRENT_TEST_METHOD_ARGUMENTS, arguments);\n\t\tfor (final PowerMockTestListener testListener : powerMockTestListeners) {\n\t\t\ttry {\n\t\t\t\ttestListener.beforeTestMethod(testInstance, testMethod, arguments);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, \"beforeTestMethod\", testListener), e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void notifyBeforeTestSuiteStarted(Class<?> testClass, Method[] testMethods) {\n\t\tfor (PowerMockTestListener powerMockTestListener : powerMockTestListeners) {\n\t\t\ttry {\n\t\t\t\tpowerMockTestListener.beforeTestSuiteStarted(testClass, testMethods);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, \"beforeTestSuiteStarted\", powerMockTestListener), e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void notifyAfterTestMethod(boolean successful) {\n\t\tfinal Object test = MockRepository.getAdditionalState(Keys.CURRENT_TEST_INSTANCE);\n\t\tfinal Method testMethod = MockRepository.getAdditionalState(Keys.CURRENT_TEST_METHOD);\n\t\tfinal Object[] testArguments = MockRepository.getAdditionalState(Keys.CURRENT_TEST_METHOD_ARGUMENTS);\n\t\tfinal TestMethodResult testResult = new TestMethodResultImpl((successful ? Result.SUCCESSFUL : Result.FAILED));\n\t\tnotifyAfterTestMethod(test, testMethod, testArguments, testResult);\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.core.IndicateReloadClass;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;\nimport org.powermock.tests.utils.TestClassesExtractor;\n\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Method;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\n\n/**\n * Implementation of the {@link TestClassesExtractor} interface that extract\n * classes from the {@link PrepareForTest} or {@link PrepareOnlyThisForTest}\n * annotations. It also adds the test case to the array of classes that should\n * be modified.\n * \n */\npublic class PrepareForTestExtractorImpl extends AbstractTestClassExtractor {\n\n    public PrepareForTestExtractorImpl(){\n        this(false);\n    }\n\n    public PrepareForTestExtractorImpl(boolean includeMethods) {\n        super(includeMethods);\n    }\n\n    @Override\n    protected String[] getClassesToModify(AnnotatedElement element) {\n        Set<String> all = new LinkedHashSet<String>();\n        addTestCase(all, element);\n        PrepareForTest prepareForTestAnnotation = element.getAnnotation(PrepareForTest.class);\n        PrepareOnlyThisForTest prepareOnlyThisForTestAnnotation = element.getAnnotation(PrepareOnlyThisForTest.class);\n        final boolean prepareForTestAnnotationPresent = prepareForTestAnnotation != null;\n        final boolean prepareOnlyThisForTestAnnotationPresent = prepareOnlyThisForTestAnnotation != null;\n\n        if (!prepareForTestAnnotationPresent && !prepareOnlyThisForTestAnnotationPresent) {\n            return null;\n        }\n\n        if (prepareForTestAnnotationPresent) {\n            final Class<?>[] classesToMock = prepareForTestAnnotation.value();\n            for (Class<?> classToMock : classesToMock) {\n                if (!classToMock.equals(IndicateReloadClass.class)) {\n                    addClassHierarchy(all, classToMock);\n                }\n            }\n\n            addFullyQualifiedNames(all, prepareForTestAnnotation);\n        }\n\n        if (prepareOnlyThisForTestAnnotationPresent) {\n            final Class<?>[] classesToMock = prepareOnlyThisForTestAnnotation.value();\n            for (Class<?> classToMock : classesToMock) {\n                if (!classToMock.equals(IndicateReloadClass.class)) {\n                    all.add(classToMock.getName());\n                }\n            }\n\n            addFullyQualifiedNames(all, prepareOnlyThisForTestAnnotation);\n        }\n\n        return all.toArray(new String[all.size()]);\n\n    }\n\n    private void addTestCase(Set<String> all, AnnotatedElement element) {\n        Class<?> testClass = null;\n        if (element instanceof Class<?>) {\n            testClass = (Class<?>) element;\n        } else if (element instanceof Method) {\n            testClass = ((Method) element).getDeclaringClass();\n        }\n        addClassHierarchy(all, testClass);\n    }\n\n    private void addFullyQualifiedNames(Set<String> all, PrepareForTest annotation) {\n        String[] fullyQualifiedNames = annotation.fullyQualifiedNames();\n        addFullyQualifiedNames(all, fullyQualifiedNames);\n    }\n\n    private void addFullyQualifiedNames(Set<String> all, PrepareOnlyThisForTest annotation) {\n        String[] fullyQualifiedNames = annotation.fullyQualifiedNames();\n        addFullyQualifiedNames(all, fullyQualifiedNames);\n    }\n\n    private void addFullyQualifiedNames(Set<String> all, String[] fullyQualifiedNames) {\n        for (String string : fullyQualifiedNames) {\n            if (!\"\".equals(string)) {\n                all.add(string);\n            }\n        }\n    }\n\n    private void addClassHierarchy(Set<String> all, Class<?> classToMock) {\n        while (classToMock != null && !classToMock.equals(Object.class)) {\n            addInnerClassesAndInterfaces(all, classToMock);\n            all.add(classToMock.getName());\n            classToMock = classToMock.getSuperclass();\n        }\n    }\n\n    private void addInnerClassesAndInterfaces(Set<String> all, Class<?> classToMock) {\n        Class<?>[] declaredClasses = classToMock.getDeclaredClasses();\n        for (Class<?> innerClass : declaredClasses) {\n            all.add(innerClass.getName());\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/StaticConstructorSuppressExtractorImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.tests.utils.TestClassesExtractor;\n\nimport java.lang.reflect.AnnotatedElement;\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * Implementation of the {@link TestClassesExtractor} interface for classes that\n * should have their static initializers suppressed.\n * \n */\npublic class StaticConstructorSuppressExtractorImpl extends AbstractTestClassExtractor {\n\n\t@Override\n\tpublic String[] getClassesToModify(AnnotatedElement element) {\n\t\tList<String> all = new LinkedList<String>();\n\n\t\tfinal SuppressStaticInitializationFor suppressAnnotation = element.getAnnotation(SuppressStaticInitializationFor.class);\n\n\t\tif (suppressAnnotation == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tfinal String[] value = suppressAnnotation.value();\n\t\t\tfor (String classToSuppress : value) {\n\t\t\t\tif (!\"\".equals(classToSuppress)) {\n\t\t\t\t\tall.add(classToSuppress);\n\t\t\t\t\tMockRepository.addSuppressStaticInitializer(classToSuppress);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn all.toArray(new String[all.size()]);\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/TestCaseEntry.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.tests.utils.TestChunk;\n\nimport java.util.List;\n\n/**\n * A test case entry consists of a test class and a list of test chunks that\n * should be executed for this entry.\n */\npublic class TestCaseEntry {\n\n\tprivate final List<TestChunk> testChunks;\n\tprivate final Class<?> testClass;\n\n\tpublic TestCaseEntry(Class<?> testClass, List<TestChunk> chunks) {\n\t\tthis.testClass = testClass;\n\t\tthis.testChunks = chunks;\n\t}\n\n\tpublic List<TestChunk> getTestChunks() {\n\t\treturn testChunks;\n\t}\n\n\tpublic Class<?> getTestClass() {\n\t\treturn testClass;\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/tests/utils/impl/TestChunkImpl.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.powermock.tests.utils.TestChunk;\n\nimport java.lang.reflect.Method;\nimport java.util.List;\n\n/**\n * A test chunk consists of a list of methods that should be executed by a\n * particular classloader.\n */\npublic class TestChunkImpl implements TestChunk {\n\n\tprivate final ClassLoader classLoader;\n\tprivate final List<Method> testMethodsToBeExecutedByThisClassloader;\n\n    public TestChunkImpl(ClassLoader classLoader, List<Method> testMethodsToBeExecutedByThisClassloader) {\n\t\tthis.classLoader = classLoader;\n\t\tthis.testMethodsToBeExecutedByThisClassloader = testMethodsToBeExecutedByThisClassloader;\n    }\n\n\t@Override\n\tpublic ClassLoader getClassLoader() {\n\t\treturn classLoader;\n\t}\n\n\t@Override\n\tpublic List<Method> getTestMethodsToBeExecutedByThisClassloader() {\n\t\treturn testMethodsToBeExecutedByThisClassloader;\n\t}\n\n    @Override\n    public boolean isMethodToBeExecutedByThisClassloader(Method method) {\n        return testMethodsToBeExecutedByThisClassloader.contains(method);\n    }\n\n    @Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"Classloader = \").append(classLoader).append(\"\\n\");\n\t\tsb.append(\"Methods:\\n\");\n\t\tfor (Method method : testMethodsToBeExecutedByThisClassloader) {\n\t\t\tsb.append(\"  \").append(method).append(\"\\n\");\n\t\t}\n\t\treturn sb.toString();\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/utils/ArrayUtil.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.utils;\n\nimport java.lang.reflect.Array;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static java.util.Arrays.asList;\n\npublic class ArrayUtil {\n\n    public static <T> T[] addAll(T[] array1, T[] array2) {\n        if (isEmpty(array1)) {\n            return clone(array2);\n        } else if (isEmpty(array2)) {\n            return clone(array1);\n        }\n        int newLength = array1.length + array2.length;\n        T[] joinedArray = createNewArrayWithSameType(array1, newLength);\n        System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n        return joinedArray;\n    }\n\n    private static <T> boolean isEmpty(T[] a) {\n        return a == null || a.length == 0;\n    }\n\n    public static <T> T[] clone(T[] array) {\n        if (array == null) {\n            return null;\n        }\n        return array.clone();\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    private static <T> T[] createNewArrayWithSameType(T[] arrayPrototype, int newLength) {\n        return (T[]) Array.newInstance(arrayPrototype[0].getClass(), newLength);\n    }\n    \n    public static String[] mergeArrays(final String[] firstArray, final String[] secondArray) {\n        \n        if (firstArray == null && secondArray == null){\n            return null;\n        }\n        \n        if (firstArray == null){\n            return secondArray;\n        }\n    \n        if (secondArray == null){\n            return firstArray;\n        }\n        \n        Set<String> globalIgnore = new HashSet<String>();\n        \n        globalIgnore.addAll(asList(firstArray));\n        globalIgnore.addAll(asList(secondArray));\n        \n        return globalIgnore.toArray(new String[globalIgnore.size()]);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/utils/Asserts.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.utils;\n\n\nimport org.powermock.PowerMockInternalException;\n\npublic class Asserts {\n    \n    public static void assertNotNull(Object value, String message){\n        if (value == null) {\n            throw new IllegalArgumentException(message);\n        }\n    }\n    \n    public static void internalAssertNotNull(Object value, String message){\n        if (value == null) {\n            throw new PowerMockInternalException(message);\n        }\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/utils/IOUtils.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.utils;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\n\npublic class IOUtils {\n    \n    public static void copyFileUsingStream(File source, File dest) throws IOException {\n        InputStream is = null;\n        OutputStream os = null;\n        try {\n            is = new FileInputStream(source);\n            os = new FileOutputStream(dest);\n            byte[] buffer = new byte[1024];\n            int length;\n            while ((length = is.read(buffer)) > 0) {\n                os.write(buffer, 0, length);\n            }\n        } finally {\n            if (is != null) {\n                is.close();\n            }\n            if (os != null) {\n                os.close();\n            }\n        }\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/utils/JavaVersion.java",
    "content": "package org.powermock.utils;\n\npublic enum JavaVersion {\n\n    /**\n     * The Java version reported by Android. This is not an official Java version number.\n     */\n    JAVA_0_9(1.5f, \"0.9\"),\n\n    /**\n     * Java 1.1.\n     */\n    JAVA_1_1(1.1f, \"1.1\"),\n\n    /**\n     * Java 1.2.\n     */\n    JAVA_1_2(1.2f, \"1.2\"),\n\n    /**\n     * Java 1.3.\n     */\n    JAVA_1_3(1.3f, \"1.3\"),\n\n    /**\n     * Java 1.4.\n     */\n    JAVA_1_4(1.4f, \"1.4\"),\n\n    /**\n     * Java 1.5.\n     */\n    JAVA_1_5(1.5f, \"1.5\"),\n\n    /**\n     * Java 1.6.\n     */\n    JAVA_1_6(1.6f, \"1.6\"),\n\n    /**\n     * Java 1.7.\n     */\n    JAVA_1_7(1.7f, \"1.7\"),\n\n    /**\n     * Java 1.8.\n     */\n    JAVA_1_8(1.8f, \"1.8\"),\n\n    /**\n     * Java 1.9.\n     *\n     * @deprecated As of release 3.5, replaced by {@link #JAVA_9}\n     */\n    @Deprecated\n    JAVA_1_9(9.0f, \"9\"),\n\n    /**\n     * Java 9\n     *\n     * @since 3.5\n     */\n    JAVA_9(9.0f, \"9\"),\n\n    /**\n     * Java 10\n     *\n     * @since 3.7\n     */\n    JAVA_10(10.0f, \"10\"),\n\n    /**\n     * Java 11\n     *\n     * @since 3.8\n     */\n    JAVA_11(11.0f, \"11\"),\n\n    /**\n     * Java 12\n     *\n     * @since 3.9\n     */\n    JAVA_12(12.0f, \"12\"),\n\n    /**\n     * Java 13\n     *\n     * @since 3.9\n     */\n    JAVA_13(13.0f, \"13\"),\n\n    /**\n     * The most recent java version. Mainly introduced to avoid to break when a new version of Java is used.\n     */\n    JAVA_RECENT(maxVersion(), Float.toString(maxVersion()));\n\n    /**\n     * The float value.\n     */\n    private final float value;\n\n    /**\n     * The standard name.\n     */\n    private final String name;\n\n    /**\n     * Constructor.\n     *\n     * @param value  the float value\n     * @param name  the standard name, not null\n     */\n    JavaVersion(final float value, final String name) {\n        this.value = value;\n        this.name = name;\n    }\n\n    //-----------------------------------------------------------------------\n    /**\n     * <p>Whether this version of Java is at least the version of Java passed in.</p>\n     *\n     * <p>For example:<br>\n     *  {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}<p>\n     *\n     * @param requiredVersion  the version to check against, not null\n     * @return true if this version is equal to or greater than the specified version\n     */\n    public boolean atLeast(final JavaVersion requiredVersion) {\n        return this.value >= requiredVersion.value;\n    }\n\n    /**\n     * Transforms the given string with a Java version number to the\n     * corresponding constant of this enumeration class. This method is used\n     * internally.\n     *\n     * @param nom the Java version as string\n     * @return the corresponding enumeration constant or <b>null</b> if the\n     * version is unknown\n     */\n    static JavaVersion get(final String nom) {\n        if (\"0.9\".equals(nom)) {\n            return JAVA_0_9;\n        } else if (\"1.1\".equals(nom)) {\n            return JAVA_1_1;\n        } else if (\"1.2\".equals(nom)) {\n            return JAVA_1_2;\n        } else if (\"1.3\".equals(nom)) {\n            return JAVA_1_3;\n        } else if (\"1.4\".equals(nom)) {\n            return JAVA_1_4;\n        } else if (\"1.5\".equals(nom)) {\n            return JAVA_1_5;\n        } else if (\"1.6\".equals(nom)) {\n            return JAVA_1_6;\n        } else if (\"1.7\".equals(nom)) {\n            return JAVA_1_7;\n        } else if (\"1.8\".equals(nom)) {\n            return JAVA_1_8;\n        } else if (\"9\".equals(nom)) {\n            return JAVA_9;\n        } else if (\"10\".equals(nom)) {\n            return JAVA_10;\n        } else if (\"11\".equals(nom)) {\n            return JAVA_11;\n        } else if (\"12\".equals(nom)) {\n            return JAVA_12;\n        } else if (\"13\".equals(nom)) {\n            return JAVA_13;\n        }\n        if (nom == null) {\n            return null;\n        }\n        final float v = toFloatVersion(nom);\n        if ((v - 1.) < 1.) { // then we need to check decimals > .9\n            final int firstComma = Math.max(nom.indexOf('.'), nom.indexOf(','));\n            final int end = Math.max(nom.length(), nom.indexOf(',', firstComma));\n            if (Float.parseFloat(nom.substring(firstComma + 1, end)) > .9f) {\n                return JAVA_RECENT;\n            }\n        } else if (v > 10) {\n            return JAVA_RECENT;\n        }\n        return null;\n    }\n\n    //-----------------------------------------------------------------------\n    /**\n     * <p>The string value is overridden to return the standard name.</p>\n     *\n     * <p>For example, <code>\"1.5\"</code>.</p>\n     *\n     * @return the name, not null\n     */\n    @Override\n    public String toString() {\n        return name;\n    }\n\n    /**\n     * Gets the Java Version from the system or 99.0 if the {@code java.specification.version} system property is not set.\n     *\n     * @return the value of {@code java.specification.version} system property or 99.0 if it is not set.\n     */\n    private static float maxVersion() {\n        final float v = toFloatVersion(System.getProperty(\"java.specification.version\", \"99.0\"));\n        if (v > 0) {\n            return v;\n        }\n        return 99f;\n    }\n\n    /**\n     * Parses a float value from a String.\n     *\n     * @param value the String to parse.\n     * @return the float value represented by the string or -1 if the given String can not be parsed.\n     */\n    private static float toFloatVersion(final String value) {\n        final int defaultReturnValue = -1;\n        if (value.contains(\".\")) {\n            final String[] toParse = value.split(\"\\\\.\");\n            if (toParse.length >= 2) {\n                return NumberUtils.toFloat(toParse[0] + '.' + toParse[1], defaultReturnValue);\n            }\n        } else {\n            return NumberUtils.toFloat(value, defaultReturnValue);\n        }\n        return defaultReturnValue;\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/utils/NumberUtils.java",
    "content": "package org.powermock.utils;\n\npublic class NumberUtils {\n    public static float toFloat(final String str, final float defaultValue) {\n        if (str == null) {\n            return defaultValue;\n        }\n        try {\n            return Float.parseFloat(str);\n        } catch (final NumberFormatException nfe) {\n            return defaultValue;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/main/java/org/powermock/utils/StringJoiner.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.utils;\n\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class StringJoiner {\n    \n    private static final String LINE_SEPARATOR = System.getProperty(\"line.separator\");\n    private static final String EMPTY_STRING = \"\";\n    \n    \n    public static String join(Object... linesToBreak) {\n        StringBuilder out = new StringBuilder(LINE_SEPARATOR);\n        return join(out, Arrays.asList(linesToBreak), LINE_SEPARATOR);\n    }\n    \n    public static <T> String join(List<T> list) {\n        StringBuilder out = new StringBuilder(LINE_SEPARATOR);\n        return join(out, list, LINE_SEPARATOR);\n    }\n    \n    public static String join(String separator, Object... linesToBreak) {\n        StringBuilder out = new StringBuilder();\n        return join(out, linesToBreak, separator);\n    }\n    \n    private static String join(StringBuilder out, Iterable linesToBreak, final String separator) {\n        for (Object line : linesToBreak) {\n            out.append(line.toString()).append(separator);\n        }\n        int lastBreak = out.lastIndexOf(separator);\n        return out.replace(lastBreak, lastBreak + 1, EMPTY_STRING).toString();\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/main/resources/org/powermock/default.properties",
    "content": "# suppress inspection \"UnusedProperty\" for whole file\npowermock.global-ignore=org.powermock.core*\npowermock.byte-code-framework=Javassist"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/WildcardMatcherTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock;\n\nimport org.junit.Test;\nimport org.powermock.core.WildcardMatcher;\n\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\npublic class WildcardMatcherTest {\n\n    @Test\n    public void matchesWildcardOnBothEnds() throws Exception {\n        assertTrue(WildcardMatcher.matches(\"org.mytest.java\", \"*.java*\"));\n    }\n\n    @Test\n    public void matchesWildcardSuffix() throws Exception {\n        assertTrue(WildcardMatcher.matches(\"org.mytest.java\", \"*.java\"));\n    }\n\n    @Test\n    public void doesntMatchWildcardPrefix() throws Exception {\n        assertFalse(WildcardMatcher.matches(\"org.mytest.java\", \".java*\"));\n    }\n    \n    @Test\n    public void convertsDotsAndWildcardsToRegExp() throws Exception {\n        assertFalse(WildcardMatcher.matches(\"javassist.runtime.Desc\", \"java.*\"));\n    }\n\n    @Test\n    public void noWildcardCardPrefix() throws Exception {\n        assertFalse(WildcardMatcher.matches(\"org.mytest.java\", \".java\"));\n    }\n    @Test\n    public void exactMatch() throws Exception {\n        assertTrue(WildcardMatcher.matches(\"org.mytest.java\", \"org.mytest.java\"));\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationBuilderTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration.support;\n\nimport org.junit.Test;\nimport org.powermock.configuration.Configuration;\nimport org.powermock.configuration.MockitoConfiguration;\nimport org.powermock.configuration.PowerMockConfiguration;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.configuration.support.ConfigurationBuilder.createConfigurationFor;\n\npublic class ConfigurationBuilderTest {\n    \n    private static final String CONF_PATH = \"org/powermock/extensions\";\n    private static final String CONFIGURATION_FILE = CONF_PATH + \"/test.properties\";\n\n    \n    @Test\n    public void should_create_configuration_from_file() {\n    \n        final Configuration configuration = createConfigurationFor(MockitoConfiguration.class)\n                                                .fromFile(CONFIGURATION_FILE);\n        \n        assertThat(configuration)\n            .as(\"Configuration is map\")\n            .isNotNull();\n    }\n    \n    @Test\n    public void should_read_mock_maker_class_from_configuration() {\n        final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class)\n                                                       .fromFile(CONFIGURATION_FILE);\n    \n        assertThat(configuration.getMockMakerClass())\n            .as(\"Configuration is map\")\n            .isEqualTo(\"TestMockMaker\");\n    }\n    \n    @Test\n    public void should_not_read_mock_maker_class_from_configuration_without_prefix() {\n        final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class)\n                                                       .fromFile(CONF_PATH + \"/test_without_prefix.properties\");\n    \n        assertThat(configuration.getMockMakerClass())\n            .as(\"Configuration is map\")\n            .isNull();\n    }\n    \n    @Test\n    public void should_return_empty_configuration__when_configuration_file_non_exist() {\n    \n        final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class)\n                                                       .fromFile(CONF_PATH + \"/test_without_prefix\");\n    \n    \n        assertThat(configuration.getMockMakerClass())\n            .as(\"Configuration is null.\")\n            .isNull();\n    }\n    \n    @Test\n    public void should_return_real_value_instead_alias() {\n    \n        final String value = \"value\";\n    \n        final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class)\n                                                       .withValueAlias(\"alias\", value)\n                                                       .fromFile(CONF_PATH + \"/test_with_alias.properties\");\n    \n        assertThat(configuration.getMockMakerClass())\n            .as(\"Configuration is map\")\n            .isEqualTo(value);\n    }\n    \n    @Test\n    public void should_read_powermock_global_ignore_as_array() {\n    \n        PowerMockConfiguration configuration = createConfigurationFor(PowerMockConfiguration.class)\n                                                   .fromFile(CONFIGURATION_FILE);\n    \n        assertThat(configuration.getGlobalIgnore())\n            .as(\"Configuration is map\")\n            .containsExactly(\"org.somepacckage.*\",\"org.other.Class\");\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationFactoryImplTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.configuration.support;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.contrib.java.lang.system.EnvironmentVariables;\nimport org.junit.experimental.runners.Enclosed;\nimport org.junit.runner.RunWith;\nimport org.powermock.configuration.ConfigurationFactory;\nimport org.powermock.configuration.PowerMockConfiguration;\nimport org.powermock.core.classloader.ByteCodeFramework;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\n@RunWith(Enclosed.class)\npublic class ConfigurationFactoryImplTest {\n    \n    public static class SystemPropertiesCases {\n        \n        @Rule\n        public final EnvironmentVariables environmentVariables = new EnvironmentVariables();\n        \n        private ConfigurationFactory configurationFactory;\n    \n        @Before\n        public void setUp() {\n            configurationFactory = new ConfigurationFactoryImpl(\n                \"org/powermock/extensions/test.properties\",\n                \"org/powermock/test_default_configuration.properties\"\n            );\n        }\n        \n        @Test\n        public void should_read_byte_code_framework_from_environment_variable_if_defined() {\n            environmentVariables.set(\"powermock.byte-code-framework\", ByteCodeFramework.Javassist.name());\n            \n            PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class);\n            \n            assertThat(configuration)\n                .as(\"Configuration is created\")\n                .isNotNull();\n            \n            assertThat(configuration.getByteCodeFramework())\n                .as(\"Enum from configuration is read correctly\")\n                .isEqualTo(ByteCodeFramework.Javassist);\n        }\n    }\n    \n    \n    public static class FileCases {\n        \n        private ConfigurationFactory configurationFactory;\n        \n        @Before\n        public void setUp() {\n            configurationFactory = new ConfigurationFactoryImpl(\n                \"org/powermock/extensions/test_configuration.properties\",\n                \"org/powermock/test_default_configuration.properties\"\n            );\n        }\n        \n        @Test\n        public void should_return_configuration_from_file_if_configuration_file_exist() {\n            PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class);\n            \n            assertThat(configuration)\n                .as(\"Configuration is created\")\n                .isNotNull();\n            \n            assertThat(configuration.getGlobalIgnore())\n                .as(\"Configuration is read correctly\")\n                .contains(\"org.somepackage\");\n            assertThat(configuration.getByteCodeFramework())\n                .as(\"Enum from configuration is read correctly\")\n                .isEqualTo(ByteCodeFramework.Javassist);\n        }\n        \n        @Test\n        public void should_return_default_configuration_if_configuration_file_not_exist() {\n            configurationFactory = new ConfigurationFactoryImpl(\n                \"org/powermock/test_default_configuration.properties\"\n            );\n            PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class);\n            \n            assertThat(configuration)\n                .as(\"Configuration is created\")\n                .isNotNull();\n            \n            assertThat(configuration.getGlobalIgnore())\n                .as(\"Configuration is read correctly\")\n                .contains(\"org.powermock.core*\");\n        }\n        \n        @Test\n        public void should_return_default_value_for_configuration_if_value_in_user_configuration_is_not_defined() {\n            configurationFactory = new ConfigurationFactoryImpl(\n                \"org/powermock/extensions/test.properties\",\n                \"org/powermock/test_default_configuration.properties\"\n            );\n            \n            PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class);\n            \n            assertThat(configuration)\n                .as(\"Configuration is created\")\n                .isNotNull();\n            \n            assertThat(configuration.getByteCodeFramework())\n                .as(\"Enum from configuration is read correctly\")\n                .isEqualTo(ByteCodeFramework.Javassist);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/classloader/Collaborator.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader;\n\npublic class Collaborator {\n\tprivate int count;\n\n\tpublic void doStuff(int indx) {\n\t\tcount += indx;\n\t}\n\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/classloader/HardToTransform.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader;\n\npublic class HardToTransform {\n\tpublic void run() {\n\t\tCollaborator collaborator = new Collaborator();\n\t\tfor (int indx=0; indx<10; indx++) {\n\t\t\tcollaborator.doStuff(indx);\n\t\t}\n\t}\n\tpublic int testInt() {\n\t\treturn 5;\n\t}\n\tpublic double testDouble() {\n\t\treturn 5;\n\t}\n\tpublic float testFloat() {\n\t\treturn 5;\n\t}\n\tpublic long testLong() {\n\t\treturn 5;\n\t}\n\tpublic short testShort() {\n\t\treturn 5;\n\t}\n\tpublic byte testByte() {\n\t\treturn 5;\n\t}\n\tpublic boolean testBoolean() {\n\t\treturn true;\n\t}\n\tpublic char testChar() {\n\t\treturn '5';\n\t}\n\t\n\tpublic String testString() {\n\t\treturn \"5\";\n\t}\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderBuilderTest.java",
    "content": "package org.powermock.core.classloader;\n\n\nimport javassist.CtClass;\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.powermock.PowerMockInternalException;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.MockTransformerChain.FilterPredicate;\nimport org.powermock.core.transformers.TestClassAwareTransformer;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.ParameterizedType;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.assertThatThrownBy;\n\npublic class MockClassLoaderBuilderTest {\n    \n    @Test\n    public void should_create_instance_of_MockClassLoader_depends_on_provided_bytecode_framework() {\n        MockClassLoader classLoader = MockClassLoaderBuilder\n                                          .create(ByteCodeFramework.Javassist)\n                                          .forTestClass(getClass())\n                                          .build();\n        \n        assertThat(classLoader).isExactlyInstanceOf(JavassistMockClassLoader.class);\n    }\n    \n    @Test\n    public void should_create_transformer_chain_depends_on_provided_bytecode_framework() {\n        \n        MockClassLoader classLoader = MockClassLoaderBuilder\n                                          .create(ByteCodeFramework.Javassist)\n                                          .forTestClass(getClass())\n                                          .build();\n        \n        assertThatJavassistMockTransformerChainCreated(classLoader);\n    }\n    \n    @Test\n    public void should_set_test_class_to_TestClassAwareTransformers() {\n        \n        final SpyMockTransformer extraMockTransformer = new SpyMockTransformer();\n        \n        MockClassLoaderBuilder\n            .create(ByteCodeFramework.Javassist)\n            .forTestClass(MockClassLoaderBuilderTest.class)\n            .addExtraMockTransformers(extraMockTransformer)\n            .build();\n        \n        assertThat(extraMockTransformer.testClass)\n            .as(\"Test class is set \")\n            .isEqualTo(MockClassLoaderBuilderTest.class);\n    }\n    \n    @Test\n    public void should_throw_internal_exception_if_test_class_is_null() {\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() {\n                MockClassLoaderBuilder\n                    .create(ByteCodeFramework.Javassist)\n                    .build();\n            }\n        }).as(\"Internal exception has been thrown.\")\n          .isExactlyInstanceOf(PowerMockInternalException.class);\n    }\n    \n    private void assertThatJavassistMockTransformerChainCreated(final MockClassLoader classLoader) {\n        final DefaultMockTransformerChain mockTransformerChain = (DefaultMockTransformerChain) classLoader.getMockTransformerChain();\n        assertThatMockTransformerChainWorksWithExpectedClassRepresentation(CtClass.class, mockTransformerChain);\n    }\n    \n    private void assertThatMockTransformerChainWorksWithExpectedClassRepresentation(final Class<?> expectedParameterClass,\n                                                                                    final DefaultMockTransformerChain mockTransformerChain) {\n        final Method method = WhiteboxImpl.findMethod(\n            mockTransformerChain.filter(new FilterPredicate() {\n                @Override\n                public boolean test(final MockTransformer<?> mockTransformer) {\n                    return true;\n                }\n            }).iterator().next().getClass(),\n            \"transform\",\n            ClassWrapper.class\n        );\n        \n        final ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType();\n        assertThat(returnType.getActualTypeArguments())\n            .withFailMessage(\n                \"Expected that transformer chain works with %s, however actually it works with %s\",\n                expectedParameterClass, ((Class) returnType.getActualTypeArguments()[0]).getName()\n            )\n            .containsExactly(expectedParameterClass);\n    }\n    \n    private static class SpyMockTransformer<T> implements MockTransformer<T>, TestClassAwareTransformer {\n        \n        private Class<?> testClass;\n        \n        @Override\n        public ClassWrapper<T> transform(final ClassWrapper<T> clazz) {\n            return null;\n        }\n        \n        @Override\n        public void setTestClass(final Class<?> testClass) {\n            \n            this.testClass = testClass;\n        }\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderConfigurationTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.classloader;\n\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class MockClassLoaderConfigurationTest {\n    \n    private MockClassLoaderConfiguration configuration;\n    \n    @Before\n    public void setUp() throws Exception {\n        configuration = new MockClassLoaderConfiguration();\n    }\n    \n    @Test\n    public void should_add_ignoredPackage_to_defer() {\n        final String packageToIgnore = \"test*\";\n        \n        configuration.addIgnorePackage(packageToIgnore);\n        \n        String[] deferPackages = configuration.getDeferPackages();\n        \n        assertThat(deferPackages)\n            .hasSize(MockClassLoaderConfiguration.PACKAGES_TO_BE_DEFERRED.length + 1)\n            .contains(packageToIgnore);\n    }\n    \n    @Test\n    public void classes_to_modify_should_have_precedence_over_package_to_ignore() throws Exception {\n        \n        configuration.addClassesToModify(\"org.mytest.myclass\");\n        configuration.addIgnorePackage(\"*mytest*\");\n        \n        assertThat(configuration.shouldModify(\"org.mytest.myclass\")).isTrue();\n    }\n    \n    @Test\n    public void classes_from_packages_to_modify_should_modify() throws Exception {\n    \n        configuration.addClassesToModify(\"*mytest*\");\n    \n        assertThat(configuration.shouldModify(\"org.mytest.myclass.SomeClass\")).isTrue();\n    }\n    \n    \n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderFactoryTest.java",
    "content": "package org.powermock.core.classloader;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.experimental.runners.Enclosed;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\nimport org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.ExceptionTestClass;\nimport org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.JavassistTestClass;\nimport org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.PrepareEverythingForTestTestClass;\nimport org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.SuppressStaticInitializationForTestClass;\nimport org.powermock.core.classloader.annotations.PrepareEverythingForTest;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.reflect.Whitebox;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.powermock.core.test.ContainsCondition.contains;\n\n\n@RunWith(Enclosed.class)\npublic class MockClassLoaderFactoryTest {\n    \n    @RunWith(Parameterized.class)\n    public static class AnnotationTestOnClassLevelCases extends BasePrepareForTestCases {\n    \n        public AnnotationTestOnClassLevelCases(final Class<?> testClass, String expectedClassToModify) {\n            super(testClass, expectedClassToModify);\n        }\n    \n        @Test\n        public void should_extract_classes_to_modify_from_class_level_annotation() {\n            final ClassLoader classLoader = objectUnderTest.createForClass();\n            \n            assertThat(classLoader)\n                .as(\"An instance of MockClassLoader is created\")\n                .isInstanceOf(MockClassLoader.class);\n    \n            assertThat(((MockClassLoader) classLoader).getConfiguration())\n                .as(\"MockClassLoader configuration contains expected class: %s\", expectedClassToModify)\n                .extracting(\"modify\")\n                .are(contains(expectedClassToModify));\n        }\n    }\n    \n    @RunWith(Parameterized.class)\n    public static class AnnotationOnMethodLevelCases extends BasePrepareForTestCases {\n    \n        @Parameters(name = \"Test parameter: {0}\")\n        public static Collection<Object[]> parameters() {\n            final ArrayList<Object[]> parameters = new ArrayList<Object[]>();\n        \n            parameters.add(new Object[]{JavassistTestClass.class, \"powermock.test.support.MainMockTransformerTestSupport$SupportClasses$FinalInnerClass\"});\n            parameters.add(new Object[]{SuppressStaticInitializationForTestClass.class, \"SupportClasses.FinalInnerClass\"});\n            parameters.add(new Object[]{PrepareEverythingForTestTestClass.class, \"*\"});\n        \n            return parameters;\n        }\n        \n        public AnnotationOnMethodLevelCases(final Class<?> testClass, String expectedClassToModify) {\n            super(testClass, expectedClassToModify);\n        }\n    \n        @Test\n        public void should_extract_classes_to_modify_method_level_annotation_if_exist() {\n            final Method method = Whitebox.getMethod(testClass, \"someTestWithPrepareForTest\");\n            \n            final ClassLoader classLoader = objectUnderTest.createForMethod(method);\n            \n            assertThat(classLoader)\n                .as(\"An instance of MockClassLoader is created\")\n                .isInstanceOf(MockClassLoader.class);\n            \n            assertThat(((MockClassLoader) classLoader).getConfiguration())\n                .as(\"MockClassLoader configuration contains expected class: %s\", expectedClassToModify)\n                .extracting(\"modify\")\n                .are(contains(expectedClassToModify));\n        }\n    \n    }\n    \n    @RunWith(Parameterized.class)\n    public static class DifferentByteCodeFrameworkCases {\n        @Parameters(name = \"Test parameter: {0}\")\n        public static Collection<Object[]> parameters() {\n            final ArrayList<Object[]> parameters = new ArrayList<Object[]>();\n            \n            parameters.add(new Object[]{JavassistTestClass.class, JavassistMockClassLoader.class});\n            \n            return parameters;\n        }\n        \n        private final Class<?> testClass;\n        \n        private final Class<? extends MockClassLoader> expectedClassLoaderClass;\n        private MockClassLoaderFactory objectUnderTest;\n        \n        public DifferentByteCodeFrameworkCases(final Class<?> testClass, final Class<? extends MockClassLoader> expectedClassLoaderClass) {\n            this.testClass = testClass;\n            this.expectedClassLoaderClass = expectedClassLoaderClass;\n        }\n        \n        @Before\n        public void setUp() {\n            objectUnderTest = new MockClassLoaderFactory(testClass);\n        }\n        \n        @Test\n        public void should_create_a_correct_instance_of_class_loader_depends_on_PrepareForTest_parameter_of_class() {\n            assertThat(objectUnderTest.createForClass())\n                .as(\"A classloader of the expected classes %s is created.\", expectedClassLoaderClass.getName())\n                .isExactlyInstanceOf(expectedClassLoaderClass);\n        }\n        \n        @Test\n        public void should_create_a_correct_instance_of_class_loader_depends_on_PrepareForTest_parameter_of_method() {\n            final Method method = Whitebox.getMethod(testClass, \"someTestWithPrepareForTest\");\n            \n            assertThat(objectUnderTest.createForMethod(method))\n                .as(\"A classloader of the expected classes %s is created.\", expectedClassLoaderClass.getName())\n                .isExactlyInstanceOf(expectedClassLoaderClass);\n        }\n    \n        @Test\n        public void should_create_a_correct_instance_of_class_loader_depends_and_use_PrepareForTest_from_class_if_method_does_not_have_annotation() {\n        \n            final Method method = Whitebox.getMethod(testClass, \"someTestWithoutPrepareForTest\");\n        \n            assertThat(objectUnderTest.createForMethod(method))\n                .as(\"A classloader of the expected classes %s is created.\", expectedClassLoaderClass.getName())\n                .isExactlyInstanceOf(expectedClassLoaderClass);\n        }\n    }\n    \n    public static class ExceptionCases{\n    \n        MockClassLoaderFactory objectUnderTest;\n        private Class<?> testClass;\n    \n        @Before\n        public void setUp() {\n            testClass =  ExceptionTestClass.class;\n            objectUnderTest = new MockClassLoaderFactory(testClass);\n        }\n    \n        @Test\n        public void should_throw_exception_if_trying_to_create_an_instance_of_class_loader_for_method_without_annotations_and_class_without_annotation() {\n            final Method method = Whitebox.getMethod(testClass, \"someTestWithoutPrepareForTest\");\n        \n            assertThatThrownBy(new ThrowingCallable() {\n                @Override\n                public void call() {\n                    objectUnderTest.createForMethod(method);\n                }\n            }).as(\"Exception is thrown.\")\n              .isExactlyInstanceOf(IllegalArgumentException.class);\n        \n        }\n\n    }\n    \n    public abstract static class BasePrepareForTestCases {\n    \n        @Parameters(name = \"Test parameter: {0}\")\n        public static Collection<Object[]> parameters() {\n            final ArrayList<Object[]> parameters = new ArrayList<Object[]>();\n            \n            parameters.add(new Object[]{JavassistTestClass.class, \"powermock.test.support.MainMockTransformerTestSupport$SupportClasses\"});\n            parameters.add(new Object[]{SuppressStaticInitializationForTestClass.class, \"SupportClasses.FinalInnerClass\"});\n            parameters.add(new Object[]{PrepareEverythingForTestTestClass.class, \"*\"});\n            \n            return parameters;\n        }\n    \n        MockClassLoaderFactory objectUnderTest;\n        \n        final String expectedClassToModify;\n        final Class<?> testClass;\n    \n        BasePrepareForTestCases(final Class<?> testClass, String expectedClassToModify) {\n            this.testClass = testClass;\n            this.expectedClassToModify = expectedClassToModify;\n        }\n    \n        @Before\n        public void setUp() {\n            objectUnderTest = new MockClassLoaderFactory(testClass);\n        }\n    }\n    \n    @SuppressWarnings(\"WeakerAccess\")\n    public abstract static class TestContainer {\n        \n        @PrepareForTest(SupportClasses.class)\n        public static class JavassistTestClass {\n            \n            @Test\n            @PrepareForTest(SupportClasses.FinalInnerClass.class)\n            public void someTestWithPrepareForTest() {\n            }\n            \n            @Test\n            public void someTestWithoutPrepareForTest() {\n            }\n            \n        }\n        \n        @PrepareEverythingForTest\n        public static class PrepareEverythingForTestTestClass {\n            \n            @Test\n            @PrepareEverythingForTest\n            public void someTestWithPrepareForTest() {\n            }\n            \n            @Test\n            public void someTestWithoutPrepareForTest() {\n            }\n            \n        }\n        \n        \n        @SuppressStaticInitializationFor(\"SupportClasses.FinalInnerClass\")\n        public static class SuppressStaticInitializationForTestClass {\n            \n            @Test\n            @SuppressStaticInitializationFor(\"SupportClasses.FinalInnerClass\")\n            public void someTestWithPrepareForTest() {\n            }\n            \n            @Test\n            public void someTestWithoutPrepareForTest() {\n            }\n            \n        }\n        \n        public static class ExceptionTestClass {\n            @Test\n            public void someTestWithoutPrepareForTest() {\n            }\n        }\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.classloader;\n\nimport javassist.ByteArrayClassPath;\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport javassist.CtMethod;\nimport net.bytebuddy.description.type.TypeDescription;\nimport net.bytebuddy.dynamic.DynamicType.Builder;\nimport net.bytebuddy.implementation.FixedValue;\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\nimport org.powermock.core.classloader.javassist.ClassPathAdjuster;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.MockTransformer;\nimport org.powermock.core.transformers.MockTransformerChain;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.List;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static java.util.Arrays.asList;\nimport static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assume.assumeThat;\nimport static org.powermock.core.classloader.MockClassLoader.MODIFY_ALL_CLASSES;\n\n@RunWith(Parameterized.class)\npublic class MockClassLoaderTest {\n    \n    \n    @Parameterized.Parameters(name = \"ClassLoader: {0}\")\n    public static List<Object[]> data() {\n        final Object[] objects = {\n            JavassistMockClassLoader.class,\n            new JavassistMockTransformer()\n        };\n        return asList(new Object[][]{objects});\n    }\n    \n    private final MockClassLoaderFactory mockClassLoaderFactory;\n    private final Class<? extends MockClassLoader> clazz;\n    private final MockTransformerChain mockTransformerChain;\n    \n    public MockClassLoaderTest(Class<? extends MockClassLoader> clazz, MockTransformer transformer) {\n        this.mockClassLoaderFactory = new MockClassLoaderFactory(clazz);\n        this.clazz = clazz;\n        this.mockTransformerChain = DefaultMockTransformerChain.newBuilder()\n                                                          .append(transformer)\n                                                          .build();\n    }\n    \n    @Test\n    public void should_load_and_modify_class_from_package_which_specified() throws Exception {\n        \n        String className = \"powermock.test.support.ClassForMockClassLoaderTestCase\";\n        \n        MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{\n            className\n        });\n        mockClassLoader.setMockTransformerChain(mockTransformerChain);\n        \n        Class<?> clazz = Class.forName(className, false, mockClassLoader);\n        \n        assertClassIsLoaded(clazz, mockClassLoader);\n        \n        assertThatInstanceCouldBeCreateAndMethodReturnMockedValue(clazz);\n    }\n    \n    @Test\n    public void should_load_and_not_modify_class_from_package_which_are_not_specified_as_ignored_or_class_to_mock() throws Exception {\n        \n        String className = \"powermock.test.support.ClassForMockClassLoaderTestCase\";\n        \n        MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);\n        mockClassLoader.setMockTransformerChain(mockTransformerChain);\n        \n        Class<?> clazz = Class.forName(className, false, mockClassLoader);\n        \n        assertClassIsLoaded(clazz, mockClassLoader);\n        \n        assertThatInstanceCouldBeCreateAndMethodReturnNotMockedValue(clazz);\n    }\n    \n    @Test\n    public void should_load_system_classes() throws Exception {\n        MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{\"org.mytest.myclass\"});\n        \n        Class<?> clazz = Class.forName(\"java.lang.String\", false, mockClassLoader);\n        \n        assertThat(clazz)\n            .as(\"System class is loaded\")\n            .isEqualTo(String.class);\n    }\n    \n    \n    @Test\n    public void should_load_defined_class() throws Exception {\n        final String className = \"my.ABCTestClass\";\n        final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{className});\n        \n        Whitebox.invokeMethod(mockClassLoader, \"defineClass\", className, DynamicClassHolder.classBytes,\n                              0, DynamicClassHolder.classBytes.length, this.getClass().getProtectionDomain());\n        \n        Class<?> clazz = Class.forName(className, false, mockClassLoader);\n        \n        assertThat(clazz)\n            .as(\"Defined class is loaded\")\n            .isNotNull();\n    }\n    \n    @Test\n    public void should_ignore_pagackage_added_powerMockIgnore_Annotated() throws Exception {\n        MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{\"org.ikk.Jux\"});\n        \n        MockClassLoaderConfiguration configuration = mockClassLoader.getConfiguration();\n        \n        Whitebox.setInternalState(configuration, \"deferPackages\", new String[]{\"*mytest*\"}, MockClassLoaderConfiguration.class);\n        \n        assertFalse(configuration.shouldModify(\"org.mytest.myclass\"));\n    }\n    \n    @Test\n    public void powerMockIgnoreAnnotatedPackagesHavePrecedenceOverPrepareEverythingForTest() throws Exception {\n        MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{MODIFY_ALL_CLASSES});\n        MockClassLoaderConfiguration configuration = mockClassLoader.getConfiguration();\n        \n        Whitebox.setInternalState(configuration, \"deferPackages\", new String[]{\"*mytest*\"}, MockClassLoaderConfiguration.class);\n        \n        assertFalse(configuration.shouldModify(\"org.mytest.myclass\"));\n    }\n    \n    @Test\n    public void should_find_and_return_a_one_resource_which_exist() throws Exception {\n        final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);\n        \n        // Force a ClassLoader that can find 'foo/bar/baz/test.txt' into\n        // mockClassLoader.deferTo.\n        mockClassLoader.deferTo = new ResourcePrefixClassLoader(getClass().getClassLoader(), \"org/powermock/core/classloader/\");\n        \n        // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it\n        // properly defers the resource lookup to its deferTo ClassLoader.\n        URL resource = mockClassLoader.getResource(\"foo/bar/baz/test.txt\");\n        assertThat(resource).isNotNull();\n        assertThat(resource.getPath()).endsWith(\"test.txt\");\n    }\n    \n    @Test\n    public void should_find_and_return_resources_which_exist() throws Exception {\n        final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);\n        \n        // Force a ClassLoader that can find 'foo/bar/baz/test.txt' into\n        // mockClassLoader.deferTo.\n        mockClassLoader.deferTo = new ResourcePrefixClassLoader(getClass().getClassLoader(), \"org/powermock/core/classloader/\");\n        \n        // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it\n        // properly defers the resources lookup to its deferTo ClassLoader.\n        Enumeration<URL> resources = mockClassLoader.getResources(\"foo/bar/baz/test.txt\");\n        \n        assertThat(resources.nextElement().getPath()).endsWith(\"test.txt\");\n    }\n    \n    @Test\n    public void resourcesNotDoubled() throws Exception {\n        final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);\n        //mockClassLoader.setMockTransformerChain(transformerChain);\n        \n        // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it\n        // properly defers the resources lookup to its deferTo ClassLoader.\n        Enumeration<URL> resources = mockClassLoader.getResources(\"org/powermock/core/classloader/foo/bar/baz/test.txt\");\n        \n        assertThat(resources.nextElement().getPath()).endsWith(\"test.txt\");\n        assertThat(resources.hasMoreElements()).isFalse();\n    }\n    \n    @Test\n    public void canFindDynamicClassFromAdjustedClasspath() throws Exception {\n        \n        assumeThat(clazz.getName(), equalTo(JavassistMockClassLoader.class.getName()));\n        \n        // Construct MockClassLoader with @UseClassPathAdjuster annotation.\n        // It activates our MyClassPathAdjuster class which appends our dynamic\n        // class to the MockClassLoader's classpool.\n        UseClassPathAdjuster useClassPathAdjuster = new TestUseClassPathAdjuster();\n        final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0], useClassPathAdjuster);\n        \n        // setup custom classloader providing our dynamic class, for MockClassLoader to defer to\n        mockClassLoader.deferTo = new ClassLoader(getClass().getClassLoader()) {\n            @Override\n            public Class<?> loadClass(String name)\n                throws ClassNotFoundException {\n                if (name.equals(DynamicClassHolder.clazz.getName())) {\n                    return DynamicClassHolder.clazz;\n                }\n                return super.loadClass(name);\n            }\n        };\n        \n        // verify that MockClassLoader can successfully load the class\n        Class<?> dynamicTestClass = Class.forName(DynamicClassHolder.clazz.getName(), false, mockClassLoader);\n        \n        assertThat(dynamicTestClass).isNotSameAs(DynamicClassHolder.clazz);\n    }\n    \n    @Test(expected = ClassNotFoundException.class)\n    @Ignore(\"Has to be decided desirable behaviour in this case\")\n    public void should_throw_ClassNotFoundException_if_cannot_find_dynamic_class_in_deferred_class_loader() throws Exception {\n        \n        MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]);\n        \n        // setup custom classloader providing our dynamic class, for MockClassLoader to defer to\n        mockClassLoader.deferTo = new ClassLoader(getClass().getClassLoader()) {\n            @Override\n            public Class<?> loadClass(String name) throws ClassNotFoundException {\n                return super.loadClass(name);\n            }\n        };\n        \n        //Try to locate and load a class that is not in MockClassLoader.\n        Class.forName(DynamicClassHolder.clazz.getName(), false, mockClassLoader);\n    }\n    \n    @Test\n    public void should_autobox_primitive_values() throws Exception {\n        String name = this.getClass().getPackage().getName() + \".HardToTransform\";\n        final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{name});\n        \n        Class<?> c = mockClassLoader.loadClass(name);\n        \n        Object object = c.newInstance();\n        Whitebox.invokeMethod(object, \"run\");\n        \n        assertThat(5).isEqualTo(Whitebox.invokeMethod(object, \"testInt\"));\n        assertThat(5L).isEqualTo(Whitebox.invokeMethod(object, \"testLong\"));\n        assertThat(5f).isEqualTo(Whitebox.invokeMethod(object, \"testFloat\"));\n        assertThat(5.0).isEqualTo(Whitebox.invokeMethod(object, \"testDouble\"));\n        assertThat(new Short(\"5\")).isEqualTo(Whitebox.invokeMethod(object, \"testShort\"));\n        assertThat(new Byte(\"5\")).isEqualTo(Whitebox.invokeMethod(object, \"testByte\"));\n        assertThat(true).isEqualTo(Whitebox.invokeMethod(object, \"testBoolean\"));\n        assertThat('5').isEqualTo(Whitebox.invokeMethod(object, \"testChar\"));\n        assertThat(\"5\").isEqualTo(Whitebox.invokeMethod(object, \"testString\"));\n    }\n    \n    \n    private void assertThatInstanceCouldBeCreateAndMethodReturnMockedValue(final Class<?> clazz) throws Exception {\n        Object instance = Whitebox.newInstance(clazz);\n        \n        assertThat(instance)\n            .as(\"Instance of class is created.\")\n            .isNotNull();\n        \n        assertThat((String) Whitebox.invokeMethod(instance, \"description\"))\n            .as(\"Method of instance of loaded class returns mocked value.\")\n            .isNull();\n    }\n    \n    private void assertThatInstanceCouldBeCreateAndMethodReturnNotMockedValue(final Class<?> clazz) throws Exception {\n        Object instance = Whitebox.newInstance(clazz);\n    \n        assertThat(instance)\n            .as(\"Instance of class is created.\")\n            .isNotNull();\n    \n        assertThat((String) Whitebox.invokeMethod(instance, \"description\"))\n            .as(\"Method of instance of loaded class returns not mocked value.\")\n            .isNotNull();\n    }\n    \n    private void assertClassIsLoaded(final Class<?> clazz, final MockClassLoader mockClassLoader) {\n        assertThat(clazz)\n            .as(\"Test class is loaded.\")\n            .isNotNull();\n        \n        assertThat(clazz.getClassLoader())\n            .as(\"Class is loaded by mock classloader\")\n            .isSameAs(mockClassLoader);\n    }\n    \n    \n    // helper class for canFindDynamicClassFromAdjustedClasspath()\n    public static class MyClassPathAdjuster implements ClassPathAdjuster {\n        public void adjustClassPath(ClassPool classPool) {\n            classPool.appendClassPath(new ByteArrayClassPath(DynamicClassHolder.clazz.getName(), DynamicClassHolder.classBytes));\n        }\n    }\n    \n    // helper class for canFindDynamicClassFromAdjustedClasspath()\n    static class DynamicClassHolder {\n        final static byte[] classBytes;\n        final static Class<?> clazz;\n        \n        static {\n            try {\n                // construct a new class dynamically\n                ClassPool cp = ClassPool.getDefault();\n                final CtClass ctClass = cp.makeClass(\"my.ABCTestClass\");\n                classBytes = ctClass.toBytecode();\n                clazz = ctClass.toClass();\n            } catch (Exception e) {\n                throw new RuntimeException(\"Problem constructing custom class\", e);\n            }\n        }\n    }\n    \n    public static class TestUseClassPathAdjuster implements UseClassPathAdjuster {\n        public Class<? extends Annotation> annotationType() {\n            return UseClassPathAdjuster.class;\n        }\n        \n        public Class<? extends ClassPathAdjuster> value() {\n            return MyClassPathAdjuster.class;\n        }\n    }\n    \n    private static class JavassistMockTransformer implements MockTransformer<CtClass> {\n        \n        @Override\n        public ClassWrapper<CtClass> transform(final ClassWrapper<CtClass> clazz) throws Exception {\n            \n            CtClass ctClass = clazz.unwrap();\n            \n            for (CtMethod ctMethod : ctClass.getMethods()) {\n                CtClass returnType = ctMethod.getReturnType();\n                if (returnType.getName().equals(String.class.getName())) {\n                    ctMethod.setBody(\"return null;\");\n                }\n            }\n            \n            return clazz;\n        }\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/classloader/ResourcePrefixClassLoader.java",
    "content": "package org.powermock.core.classloader;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Enumeration;\n\n@SuppressWarnings(\"SameParameterValue\")\npublic class ResourcePrefixClassLoader extends ClassLoader {\n\n    private final String prefix;\n\n    public ResourcePrefixClassLoader(ClassLoader parent, String prefix) {\n        super(parent);\n        this.prefix = prefix;\n    }\n\n    @Override\n    protected Enumeration<URL> findResources(String name) throws IOException {\n        // default super behaviour returns null, we want to delegate to our parent, with a prefix\n        return getParent().getResources(this.prefix + name);\n    }\n\n    @Override\n    protected URL findResource(String name) {\n        return getParent().getResource(this.prefix + name);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/test/ClassLoaderTestHelper.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.test;\n\nimport javassist.ClassPool;\nimport javassist.Loader;\nimport org.powermock.configuration.GlobalConfiguration;\nimport org.powermock.configuration.PowerMockConfiguration;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.transformers.MockTransformerChain;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static org.junit.Assert.assertNotNull;\n\npublic class ClassLoaderTestHelper {\n    \n    public static Map<MockClassLoaderFactory, Map<MockTransformerChain, MockClassLoader>> cache;\n    \n    static {\n        cache = new HashMap<MockClassLoaderFactory, Map<MockTransformerChain, MockClassLoader>>();\n    }\n    \n    public static Class<?> loadWithMockClassLoader(final String className, final MockTransformerChain mockTransformerChain,\n                                                   final MockClassLoaderFactory mockClassloaderFactory) throws Exception {\n        MockClassLoader loader = getMockClassLoader(mockTransformerChain, mockClassloaderFactory);\n        \n        Class<?> clazz = Class.forName(className, true, loader);\n        \n        assertNotNull(\"Class has been loaded\", clazz);\n        \n        return clazz;\n    }\n    \n    \n    public static Class<?> loadWithMockClassLoader(final String className, final byte[] klass, final MockTransformerChain mockTransformerChain,\n                                                   final MockClassLoaderFactory mockClassloaderFactory) throws Exception {\n        MockClassLoader loader = getMockClassLoader(mockTransformerChain, mockClassloaderFactory);\n        final Class<?> definedClass = loader.defineClass(className, ClassLoaderTestHelper.class.getProtectionDomain(), klass);\n    \n        assertNotNull(\"Class has been loaded\", definedClass);\n        \n        return definedClass;\n    }\n    \n    private static MockClassLoader getMockClassLoader(final MockTransformerChain mockTransformerChain,\n                                                      final MockClassLoaderFactory mockClassloaderFactory) throws IllegalAccessException, InvocationTargetException, InstantiationException {\n        MockClassLoader loader = null;\n        \n        Map<MockTransformerChain, MockClassLoader> classloaders = cache.get(mockClassloaderFactory);\n        \n        if (classloaders != null){\n            loader = classloaders.get(mockTransformerChain);\n        }else{\n            classloaders = new HashMap<MockTransformerChain, MockClassLoader>();\n            cache.put(mockClassloaderFactory, classloaders);\n        }\n        \n        if (loader == null) {\n            loader = mockClassloaderFactory.getInstance(new String[]{MockClassLoader.MODIFY_ALL_CLASSES});\n            loader.setMockTransformerChain(mockTransformerChain);\n            classloaders.put(mockTransformerChain, loader);\n        }\n        return loader;\n    }\n    \n    public static void runTestWithNewClassLoader(ClassPool classPool, String name) throws Throwable {\n        Loader loader = new Loader(classPool);\n        loader.run(name, new String[0]);\n    }\n    \n    \n    public static void clearCache() {\n        cache.clear();\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/test/ContainsCondition.java",
    "content": "package org.powermock.core.test;\n\nimport org.assertj.core.api.Condition;\nimport org.assertj.core.description.Description;\nimport org.powermock.core.classloader.MockClassLoaderFactoryTest;\n\nimport java.util.Collection;\n\npublic class ContainsCondition extends Condition<Object> {\n    \n    public static ContainsCondition contains(final String expectedClassToModify) {\n        return new ContainsCondition(expectedClassToModify);\n    }\n    \n    private final String expectedClassToModify;\n    \n    private ContainsCondition(final String expectedClassToModify) {\n        super(String.format(\"contains value `%s`\", expectedClassToModify));\n        this.expectedClassToModify = expectedClassToModify;\n    }\n    \n    @Override\n    public boolean matches(final Object value) {\n        Collection<String> strings = (Collection<String>) value;\n        return strings.contains(expectedClassToModify);\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/test/MockClassLoaderFactory.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.test;\n\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.classloader.MockClassLoaderConfiguration;\nimport org.powermock.core.classloader.annotations.UseClassPathAdjuster;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\n\npublic class MockClassLoaderFactory {\n    \n    private final Class<? extends MockClassLoader> classLoaderClass;\n    \n    public MockClassLoaderFactory(Class<? extends MockClassLoader> classLoaderClass) {\n        this.classLoaderClass = classLoaderClass;\n    }\n    \n    public MockClassLoader getInstance(String[] classesToMock,\n                                        UseClassPathAdjuster useClassPathAdjuster) throws IllegalAccessException, InvocationTargetException, InstantiationException {\n        Constructor<?> constructor = WhiteboxImpl.getConstructor(classLoaderClass, classesToMock.getClass(), classesToMock.getClass(), UseClassPathAdjuster.class);\n        return (MockClassLoader) constructor.newInstance(classesToMock, new String[0], useClassPathAdjuster);\n    }\n    \n    public MockClassLoader getInstance(String[] classesToMock) throws IllegalAccessException, InvocationTargetException, InstantiationException {\n        MockClassLoaderConfiguration configuration = new MockClassLoaderConfiguration(classesToMock, new String[0]);\n        return getInstance(configuration);\n    }\n    \n    private MockClassLoader getInstance(MockClassLoaderConfiguration configuration) throws IllegalAccessException, InvocationTargetException, InstantiationException {\n        Constructor<?> constructor = WhiteboxImpl.getConstructor(classLoaderClass, configuration.getClass());\n        return (MockClassLoader) constructor.newInstance(new Object[]{configuration});\n    }\n    \n    public boolean isByteBuddy(){\n        return false;\n    }\n    \n    @Override\n    public String toString() {\n        return classLoaderClass.getSimpleName();\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupportTest.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.testlisteners;\n\nimport org.junit.AfterClass;\nimport org.junit.Test;\nimport org.powermock.core.testlisteners.GlobalNotificationBuildSupport.Callback;\n\nimport java.util.Collection;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.verifyNoMoreInteractions;\n\n/**\n * The design of this test-class does only allow it to be run once per JVM\n * (or more accurately \"per classloader\", in case the test-class is redefined\n * by different classloaders in some sort of test suite),\n * because it will test some class instantiation, which can only occur one per\n * class.\n */\n@SuppressWarnings({\"SameParameterValue\", \"ResultOfMethodCallIgnored\"})\npublic class GlobalNotificationBuildSupportTest {\n\n    static boolean initiationOfNormalClassIsUnderWay;\n\n    static final Callback mockCallback = mock(Callback.class);\n\n    @SuppressWarnings(\"SameParameterValue\")\n    static class NormalClass {\n        static {\n            initiationOfNormalClassIsUnderWay = true;\n            GlobalNotificationBuildSupport.testClassInitiated(NormalClass.class);\n        }\n\n        NormalClass(String dummy) {\n            GlobalNotificationBuildSupport.testInstanceCreated(this);\n        }\n\n        public NormalClass() {\n            this(\"dummy\");\n            GlobalNotificationBuildSupport.testInstanceCreated(this);\n        }\n    }\n\n    @SuppressWarnings(\"SameParameterValue\")\n    static class SubClass extends NormalClass {\n        public SubClass() {\n            super(\"dummy\");\n        }\n        public SubClass(String dummy) {\n        }\n    }\n\n    private String nestedClassName(String localName) {\n        return GlobalNotificationBuildSupportTest.class.getName() + \"$\" + localName;\n    }\n\n    private void assertNotificationOf(NormalClass normalInstance) {\n        verify(mockCallback).testInstanceCreated(normalInstance);\n        verifyNoMoreInteractions(mockCallback);\n    }\n\n    @Test\n    public void normalClassCreation() {\n\n        // Given\n        assertFalse(\"Initiation of NormalClass must not yet have commenced\",\n                initiationOfNormalClassIsUnderWay);\n        GlobalNotificationBuildSupport.prepareTestSuite(\n                nestedClassName(\"NormalClass\"), mockCallback);\n\n        /* Nothing must have happened so far ... */\n        verifyNoMoreInteractions(mockCallback);\n\n        // When\n        final NormalClass normalInstance = new NormalClass();\n\n        // Then verify life-cycle callbacks on NormalClass\n        verify(mockCallback).suiteClassInitiated(NormalClass.class);\n\n        // Then notifications of created instances are expected ...\n        assertNotificationOf(normalInstance);\n        assertNotificationOf(new NormalClass());\n        assertNotificationOf(new NormalClass());\n        assertNotificationOf(new NormalClass(\"dummy\"));\n        assertNotificationOf(new SubClass(\"dummy\"));\n        assertNotificationOf(new NormalClass(\"dummy\"));\n        assertNotificationOf(new SubClass(\"dummy\"));\n        assertNotificationOf(new NormalClass());\n\n        // Tear-down\n        GlobalNotificationBuildSupport.closeTestSuite(NormalClass.class);\n        new NormalClass(\"dummy\").toString();\n        new SubClass().hashCode();\n        verifyNoMoreInteractions(mockCallback); // Creation should no longer have any affect\n    }\n\n    /**\n     * Tests some ConcurrentHashMap functionality that\n     * {@link GlobalNotificationBuildSupport#closePendingTestSuites(Callback)}\n     * depends on.\n     */\n    @Test\n    public void removeAllFromConcurrentHashMap() {\n        ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>();\n        final Object value = new Object();\n        map.put(\"foo\", value);\n        map.put(\"bar\", value);\n        assertEquals(\"Size of concurrent hashmap\", 2, map.size());\n        Collection<?> valueToRemove = java.util.Collections.singleton(value);\n        map.values().removeAll(valueToRemove);\n        assertEquals(\"Size of concurrent hashmap after removal of values\",\n                0, map.size());\n    }\n\n    @AfterClass\n    public static void closeTestSuite() {\n        GlobalNotificationBuildSupport.closeTestSuite(NormalClass.class);\n        GlobalNotificationBuildSupport.closePendingTestSuites(mockCallback);\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/AbstractBaseMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport javassist.CtClass;\nimport org.junit.Before;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.test.ClassLoaderTestHelper;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory;\nimport org.powermock.core.transformers.mock.MockGatewaySpy;\nimport org.powermock.core.transformers.support.FilterPredicates;\n\nimport static org.junit.Assume.assumeTrue;\n\n@RunWith(Parameterized.class)\nabstract class AbstractBaseMockTransformerTest {\n    \n    static final String SYNTHETIC_METHOD_NAME = \"$synth\";\n    static final String SYNTH_FIELD = \"$_synthField\";\n    \n    protected final TransformStrategy strategy;\n    protected final MockTransformerChain mockTransformerChain;\n    protected final MockClassLoaderFactory mockClassloaderFactory;\n    \n    AbstractBaseMockTransformerTest(final TransformStrategy strategy,\n                                    final MockTransformerChain mockTransformerChain,\n                                    final MockClassLoaderFactory mockClassloaderFactory){\n        this.strategy = strategy;\n        this.mockTransformerChain = mockTransformerChain;\n        this.mockClassloaderFactory = mockClassloaderFactory;\n    }\n    \n    @Before\n    public void setUp() throws Exception {\n        ClassLoaderTestHelper.clearCache();\n        MockGatewaySpy.clear();\n        MockGatewaySpy.returnOnMethodCall(MockGateway.PROCEED);\n    }\n    \n    protected Class<?> loadWithMockClassLoader(final String name) throws Exception {\n        return ClassLoaderTestHelper.loadWithMockClassLoader(name, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    protected Class<?> loadWithMockClassLoader(final CtClass ctClass) throws Exception {\n        return ClassLoaderTestHelper.loadWithMockClassLoader(ctClass.getName(), ctClass.toBytecode(), mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    ClassWrapper<CtClass> wrap(final CtClass ctClass) {\n        return new JavaAssistClassWrapperFactory().wrap(ctClass);\n    }\n    \n    protected void assumeClassLoaderMode() {\n        assumeTrue(\"Supported only by class loader mode.\", strategy.isClassloaderMode());\n    }\n    \n    protected void assumeAgentMode() {\n        assumeTrue(\"Supported only by class loader mode.\", strategy.isAgentMode());\n    }\n    \n    protected void assumeClassLoaderIsByteBuddy() {\n        assumeTrue(\n            \"ByteBuddy implantation MockClassLoader should always add defer constructor,\" +\n                \" because ByteBuddy cannot add constructor to super class ad-hoc.\",\n            mockClassloaderFactory.isByteBuddy()\n        );\n    }\n    \n    protected void setTestClassToTransformers(final Class<?> testClass) {\n        for (MockTransformer transformer : mockTransformerChain.filter(FilterPredicates.isInstanceOf(TestClassAwareTransformer.class))) {\n            ((TestClassAwareTransformer) transformer).setTestClass(testClass);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/ClassFinalModifierMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport powermock.test.support.MainMockTransformerTestSupport.SomeInterface;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses;\n\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static java.lang.reflect.Modifier.isFinal;\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.catchThrowable;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assume.assumeThat;\n\npublic class ClassFinalModifierMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformerType: {2}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n        \n        data.addAll(MockTransformerTestHelper.createTransformerTestData(org.powermock.core.transformers.javassist.ClassFinalModifierMockTransformer.class));\n        \n        return data;\n    }\n    \n    public ClassFinalModifierMockTransformerTest(\n                                                    final TransformStrategy strategy,\n                                                    final MockTransformerChain mockTransformerChain,\n                                                    final MockClassLoaderFactory mockClassloaderFactory\n    ) {\n        super(strategy, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_remove_final_modifier_from_static_final_inner_classes_strategy_not_equals_to_inst_redefine() throws Exception {\n    \n        assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE)));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.StaticFinalInnerClass.class.getName());\n    \n        assertFalse(Modifier.isFinal(clazz.getModifiers()));\n    }\n    \n    @Test\n    public void should_nit_remove_final_modifier_from_static_final_inner_classes_equals_to_inst_redefine() throws Exception {\n        \n        assumeThat(strategy, equalTo(TransformStrategy.INST_REDEFINE));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.StaticFinalInnerClass.class.getName());\n        \n        assertThat(isFinal(clazz.getModifiers())).isTrue();\n    }\n    \n    @Test\n    public void should_remove_final_modifier_from_final_inner_classes() throws Exception {\n    \n        assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE)));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.FinalInnerClass.class.getName());\n        assertFalse(Modifier.isFinal(clazz.getModifiers()));\n    }\n    \n    @Test\n    public void should_remove_final_modifier_from_enums() throws Exception {\n    \n        assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE)));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.EnumClass.class.getName());\n        assertFalse(Modifier.isFinal(clazz.getModifiers()));\n    }\n    \n    @Test\n    public void should_remove_final_modifier_from_private_static_final_inner_classes() throws Exception {\n    \n        assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE)));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.class.getName() + \"$PrivateStaticFinalInnerClass\");\n        assertFalse(Modifier.isFinal(clazz.getModifiers()));\n    }\n    \n    @Test\n    public void should_ignore_interfaces() throws Exception {\n    \n        Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                loadWithMockClassLoader(SomeInterface.class.getName());\n            }\n        });\n        \n        assertThat(throwable).isNull();\n    }\n    \n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/ConstructorCallMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.assertj.core.api.iterable.Extractor;\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.IndicateReloadClass;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.InstrumentMockTransformer;\nimport org.powermock.core.transformers.mock.MockGatewaySpy;\nimport org.powermock.core.transformers.mock.MockGatewaySpy.MethodCall;\nimport powermock.test.support.MainMockTransformerTestSupport.ConstructorCall.SupperClassThrowsException;\nimport powermock.test.support.MainMockTransformerTestSupport.ParameterImpl;\nimport powermock.test.support.MainMockTransformerTestSupport.ParameterInterface;\nimport powermock.test.support.MainMockTransformerTestSupport.ParentTestClass;\nimport powermock.test.support.MainMockTransformerTestSupport.ParentTestClass.NestedTestClass;\nimport powermock.test.support.MainMockTransformerTestSupport.SomeInterface;\nimport powermock.test.support.MainMockTransformerTestSupport.SuperClassCallSuperConstructor;\nimport powermock.test.support.MainMockTransformerTestSupport.SuperClassCallSuperConstructorWithCast;\nimport powermock.test.support.MainMockTransformerTestSupport.SuperClassCallSuperConstructorWithVararg;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses.EnumClass;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses.MultipleConstructors;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses.PublicSuperClass;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses.SubClass;\n\nimport java.lang.reflect.Constructor;\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.assertj.core.api.Java6Assertions.catchThrowable;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assume.assumeThat;\nimport static org.powermock.core.MockGateway.PROCEED;\nimport static org.powermock.core.MockGateway.SUPPRESS;\nimport static org.powermock.core.transformers.MockTransformerTestHelper.createTransformerTestDataWithMockGateway;\n\npublic class ConstructorCallMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformerType: {2}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n    \n        data.addAll(createTransformerTestDataWithMockGateway(MockGatewaySpy.class, InstrumentMockTransformer.class));\n        \n        return data;\n    }\n    \n    public ConstructorCallMockTransformerTest(final TransformStrategy strategy,\n                                              final MockTransformerChain mockTransformerChain,\n                                              final MockClassLoaderFactory mockClassloaderFactory) {\n        super(strategy, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    \n    @Test\n    public void should_not_change_constructors_of_test_class() throws Exception {\n        assumeClassLoaderMode();\n        \n        final Class<MultipleConstructors> testClass = MultipleConstructors.class;\n        \n        setTestClassToTransformers(testClass);\n        \n        final Class<?> modifiedClass = reloadClass(testClass);\n        \n        assertThat(modifiedClass.getConstructors())\n            .hasSameSizeAs(testClass.getConstructors());\n        \n        assertThatThrownBy(\n            new ThrowingCallable() {\n                @Override\n                public void call() throws Throwable {\n                    modifiedClass.getConstructor(IndicateReloadClass.class);\n                }\n            }\n        ).withFailMessage(\"A public defer-constructor is added.\")\n         .isExactlyInstanceOf(NoSuchMethodException.class);\n    }\n    \n    @Test\n    public void should_not_change_constructors_of_nested_test_classes() throws Exception {\n        assumeClassLoaderMode();\n    \n        setTestClassToTransformers(ParentTestClass.class);\n    \n        final Class<?> originalClazz = NestedTestClass.class;\n        final Class<?> modifiedClass = reloadClass(originalClazz);\n        \n        assertThat(modifiedClass.getConstructors())\n            .hasSameSizeAs(originalClazz.getConstructors());\n        \n        assertThatThrownBy(\n            new ThrowingCallable() {\n                @Override\n                public void call() throws Throwable {\n                    modifiedClass.getConstructor(IndicateReloadClass.class);\n                }\n            }\n        ).withFailMessage(\"A public defer-constructor is added.\")\n         .isExactlyInstanceOf(NoSuchMethodException.class);\n    }\n    \n    @Test\n    public void should_add_additional_defer_constructor_which_call_default_if_parent_Object_and_strategy_classloader() throws Exception {\n        \n        assumeClassLoaderMode();\n        assumeClassLoaderIsByteBuddy();\n        \n        Class<?> clazz = reloadClass(PublicSuperClass.class);\n        \n        assertThat(clazz.getConstructors())\n            .as(\"Number of constructors in modified class\")\n            .hasSize(2);\n        \n        assertThat(clazz.getConstructor(IndicateReloadClass.class))\n            .as(\"Defer-constructor returnOnMethodCall\")\n            .isNotNull();\n    }\n    \n    @Test\n    public void should_add_additional_defer_constructor_which_call_default_if_parent_not_Object_and_strategy_classloader() throws Exception {\n        \n        assumeClassLoaderMode();\n        \n        Class<?> clazz = reloadClass(SubClass.class);\n        \n        assertThat(clazz.getConstructors())\n            .as(\"Number of constructors in modified class\")\n            .hasSize(2);\n        \n        assertThat(clazz.getConstructor(IndicateReloadClass.class))\n            .as(\"Defer-constructor returnOnMethodCall\")\n            .isNotNull();\n    }\n    \n    @Test\n    public void should_not_add_additional_defer_constructor_if_strategy_is_not_classloader() throws Exception {\n        assumeAgentMode();\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.SubClass.class.getName());\n        \n        assertThat(clazz.getConstructors())\n            .as(\"Number of constructors in modified class\")\n            .hasSameSizeAs(SupportClasses.SubClass.class.getConstructors());\n    }\n    \n    @Test\n    public void should_not_add_defer_constructor_to_interface() throws Exception {\n        Class<?> clazz = loadWithMockClassLoader(SomeInterface.class.getName());\n        \n        assertThat(clazz.getConstructors())\n            .as(\"Number of constructors in modified interface same as in original\")\n            .hasSameSizeAs(SomeInterface.class.getConstructors());\n    }\n    \n    @Test\n    public void should_not_add_defer_constructor_to_enum() throws Exception {\n        Class<?> clazz = loadWithMockClassLoader(EnumClass.class.getName());\n        \n        assertThat(clazz.getConstructors())\n            .as(\"Number of constructors in modified class same as in original\")\n            .hasSameSizeAs(EnumClass.class.getConstructors());\n    }\n    \n    @Test\n    public void should_suppress_call_to_super_constructor_if_getaway_return_SUPPRESS() throws Exception {\n        assumeClassLoaderMode();\n        \n        MockGatewaySpy.returnOnMethodCall(SUPPRESS);\n        \n        Class<?> clazz = loadWithMockClassLoader(SuperClassCallSuperConstructor.class.getName());\n    \n        final Constructor<?> constructor = clazz.getConstructor(String.class, String.class, double.class);\n        \n        Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                try {\n                    constructor.newInstance(\"name\", \"field\", 100);\n                } catch (Exception e) {\n                    throw e.getCause() == null ? e : e.getCause();\n                }\n            }\n        });\n        \n        assertThat(throwable)\n            .as(\"Call to super is suppressed\")\n            .isNull();\n    }\n    \n    @Test\n    public void should_not_suppress_call_to_super_constructor_if_getaway_return_PROCEED() throws Exception {\n        assumeClassLoaderMode();\n        \n        MockGatewaySpy.returnOnMethodCall(PROCEED);\n        \n        Class<?> clazz = loadWithMockClassLoader(SuperClassCallSuperConstructor.class.getName());\n    \n        final Constructor<?> constructor = clazz.getConstructor(String.class, String.class, double.class);\n        \n        Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                try {\n                    constructor.newInstance(\"name\", \"field\", 100);\n                } catch (Exception e) {\n                    throw e.getCause() == null ? e : e.getCause();\n                }\n            }\n        });\n        \n        assertThat(throwable)\n            .as(\"Call to super is not suppressed\")\n            .isInstanceOf(IllegalArgumentException.class)\n            .hasMessage(SupperClassThrowsException.MESSAGE);\n    }\n    \n    @Test\n    public void should_provide_correct_constructor_param_and_arguments() throws Exception {\n        assumeClassLoaderMode();\n        \n        MockGatewaySpy.returnOnMethodCall(SUPPRESS);\n        \n        Class<?> clazz = loadWithMockClassLoader(SuperClassCallSuperConstructor.class.getName());\n    \n        final Constructor<?> constructor = clazz.getConstructor(String.class, String.class, double.class);\n        \n        constructor.newInstance(\"name\", \"field\", 100);\n    \n        assertThatCorrectConstructorTypeProvided();\n    \n        final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0);\n        \n        assertThat(methodCall.args)\n            .as(\"Correct constructor arguments are provided\")\n            .containsExactly(\"name\", 100.0);\n        \n        assertThat(methodCall.sig)\n            .as(\"Correct constructor signature is provided\")\n            .containsExactly(String.class, double.class);\n    }\n    \n    @Test\n    public void should_provide_correct_constructor_param_and_arguments_when_cast_required() throws Exception {\n        assumeClassLoaderMode();\n        \n        MockGatewaySpy.returnOnMethodCall(SUPPRESS);\n        \n        final Class<?> clazz = loadWithMockClassLoader(SuperClassCallSuperConstructorWithCast.class.getName());\n        \n        final Class<?> paramClass = loadWithMockClassLoader(ParameterInterface.class.getName());\n        final Object param = loadWithMockClassLoader(ParameterImpl.class.getName()).newInstance();\n        \n        final Constructor<?> constructor = clazz.getConstructor(paramClass);\n        \n        constructor.newInstance(param);\n    \n        assertThatCorrectConstructorTypeProvided();\n    \n        final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0);\n    \n        assertThat(methodCall.args)\n            .as(\"Correct constructor arguments are provided\")\n            .containsExactly(param);\n        \n        assertThat(methodCall.sig)\n            .as(\"Correct constructor signature is provided\")\n            .hasSize(1)\n            .extracting(new Extractor<Class<?>, Object>() {\n                @Override\n                public Object extract(final Class<?> input) {\n                    return input.getName();\n                }\n            })\n            .containsExactly(ParameterImpl.class.getName());\n    }\n    \n    @Test\n    public void should_provide_correct_constructor_param_and_arguments_when_parameters_vararg() throws Exception {\n        assumeClassLoaderMode();\n        \n        MockGatewaySpy.returnOnMethodCall(SUPPRESS);\n        \n        final Class<?> clazz = loadWithMockClassLoader(SuperClassCallSuperConstructorWithVararg.class.getName());\n        \n        final Class<?> paramClass = long[].class;\n        \n        final Constructor<?> constructor = clazz.getConstructor(paramClass);\n    \n        long[] params = {1, 5, 6};\n        constructor.newInstance(new Object[]{\n            params\n        });\n    \n        assertThatCorrectConstructorTypeProvided();\n    \n        final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0);\n        \n        assertThat(methodCall.args)\n            .as(\"Constructor arguments have correct size\")\n            .hasSize(1);\n        \n        assertThat((long[]) methodCall.args[0])\n            .as(\"Correct constructor arguments are provided\")\n            .containsExactly(params);\n        \n        assertThat(methodCall.sig)\n            .as(\"Correct constructor signature is provided\")\n            .hasSize(1)\n            .containsExactly(long[].class);\n    }\n    \n    private void assertThatCorrectConstructorTypeProvided() {\n        final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0);\n        assertThat(methodCall.type.getName())\n            .as(\"Correct constructor type is provided\")\n            .isEqualTo(SupperClassThrowsException.class.getName());\n    }\n    \n    private Class<?> reloadClass(final Class<?> originalClazz) throws Exception {\n        assumeThat(\"Original number of constructors equals to 1\", originalClazz.getConstructors().length, equalTo(1));\n        return loadWithMockClassLoader(originalClazz.getName());\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/ConstructorModifiersMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.ConstructorsMockTransformer;\nimport powermock.test.support.MainMockTransformerTestSupport.ParentTestClass;\nimport powermock.test.support.MainMockTransformerTestSupport.ParentTestClass.NestedTestClass;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses.MultipleConstructors;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Comparator;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.junit.Assume.assumeThat;\n\npublic class ConstructorModifiersMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformerType: {2}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n        \n        data.addAll(MockTransformerTestHelper.createTransformerTestData(ConstructorsMockTransformer.class));\n        \n        return data;\n    }\n    \n    public ConstructorModifiersMockTransformerTest(final TransformStrategy strategy,\n                                                   final MockTransformerChain mockTransformerChain,\n                                                   final MockClassLoaderFactory mockClassloaderFactory\n    ) {\n        super(strategy, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_make_all_constructor_public_if_strategy_is_classloader() throws Exception {\n        \n        assumeThat(strategy, equalTo(TransformStrategy.CLASSLOADER));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.MultipleConstructors.class.getName());\n        \n        assertThat(clazz.getConstructors())\n            .as(\"All constructor must be public\")\n            .hasSize(5)\n            .extracting(\"modifiers\")\n            .contains(Modifier.PUBLIC);\n    }\n    \n    @Test\n    public void should_leave_constructor_unchanged_if_strategy_is_not_classloader() throws Exception {\n        \n        assumeThat(strategy, not(equalTo(TransformStrategy.CLASSLOADER)));\n        \n        Class<?> clazz = SupportClasses.MultipleConstructors.class;\n        Class<?> modifiedClass = loadWithMockClassLoader(SupportClasses.MultipleConstructors.class.getName());\n    \n        assertThatAllConstructorsHaveSameModifier(clazz, modifiedClass);\n    }\n    \n    @Test\n    public void should_not_change_constructors_of_test_class() throws Exception {\n        assumeClassLoaderMode();\n        assumeClassLoaderIsByteBuddy();\n        \n        final Class<MultipleConstructors> testClass = MultipleConstructors.class;\n        \n        setTestClassToTransformers(testClass);\n        \n        Class<?> modifiedClass = loadWithMockClassLoader(testClass.getName());\n        \n        assertThatAllConstructorsHaveSameModifier(testClass, modifiedClass);\n    }\n    \n    @Test\n    public void should_not_change_constructors_of_nested_test_classes() throws Exception {\n        assumeClassLoaderMode();\n        assumeClassLoaderIsByteBuddy();\n        \n        setTestClassToTransformers(ParentTestClass.class);\n        \n        final Class<?> originalClazz = NestedTestClass.class;\n        \n        Class<?> modifiedClass = loadWithMockClassLoader(originalClazz.getName());\n        \n        assertThatAllConstructorsHaveSameModifier(originalClazz, modifiedClass);\n    }\n    \n    private void assertThatAllConstructorsHaveSameModifier(final Class<?> clazz, final Class<?> modifiedClass) {\n        assertThat(modifiedClass.getConstructors())\n            .as(\"All constructor has same modifiers\")\n            .hasSameSizeAs(clazz.getConstructors())\n            .usingElementComparator(new Comparator<Constructor<?>>() {\n                @Override\n                public int compare(final Constructor<?> o1, final Constructor<?> o2) {\n                    return o1.getModifiers() == o2.getModifiers()\n                               ? o1.getParameterTypes().length - o2.getParameterTypes().length : o1.getModifiers() - o2.getModifiers();\n                }\n            })\n            .contains(clazz.getConstructors());\n    }\n    \n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/InstrumentMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport javassist.CannotCompileException;\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport javassist.CtField;\nimport javassist.CtMethod;\nimport javassist.NotFoundException;\nimport javassist.bytecode.AccessFlag;\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.InstrumentMockTransformer;\nimport org.powermock.core.transformers.mock.MockGatewaySpy;\nimport powermock.test.support.MainMockTransformerTestSupport.SuperClassWithObjectMethod;\n\nimport java.lang.reflect.Field;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.core.test.ClassLoaderTestHelper.runTestWithNewClassLoader;\n\npublic class InstrumentMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    private static final String SYNTHETIC_FIELD_VALUE = \"Synthetic Field Value\";\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformer: {1}\")\n    public static Iterable<Object[]> data() {\n        return MockTransformerTestHelper.createTransformerTestData(\n            InstrumentMockTransformer.class\n        );\n    }\n    \n    public InstrumentMockTransformerTest(final TransformStrategy strategy, final MockTransformerChain mockTransformerChain,\n                                         final MockClassLoaderFactory mockClassloaderFactory) {\n        super(strategy, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_ignore_call_to_synthetic_field_when_instrument_call_to_method() throws Throwable {\n        final ClassPool classPool = new ClassPool(true);\n        CtClass ctClass = prepareClassesForFieldTests(classPool);\n        \n        mockTransformerChain.transform(wrap(ctClass));\n        \n        runTestWithNewClassLoader(classPool, ShouldIgnoreCallToSyntheticField.class.getName());\n    }\n    \n    \n    private CtClass prepareClassesForFieldTests(ClassPool classPool) throws NotFoundException, CannotCompileException {\n        CtClass ctClass = classPool.getCtClass(SuperClassWithObjectMethod.class.getName());\n        \n        addSyntheticField(classPool, ctClass);\n        insertCallSyntheticField(ctClass);\n        \n        return ctClass;\n    }\n    \n    private void insertCallSyntheticField(CtClass ctClass) throws CannotCompileException {\n        for (CtMethod method : ctClass.getDeclaredMethods()) {\n            method.insertBefore(\n                \"String v = \"\n                    + SYNTH_FIELD\n                    + \";\"\n                    + SYNTH_FIELD\n                    + \" = \\\"\"\n                    + method.getName()\n                    + \"\\\";\"\n            );\n        }\n    }\n    \n    private void addSyntheticField(ClassPool classPool,\n                                   CtClass ctClass) throws CannotCompileException, NotFoundException {\n        CtField field = new CtField(classPool.get(String.class.getName()), SYNTH_FIELD, ctClass);\n        field.setModifiers(AccessFlag.SYNTHETIC);\n        \n        ctClass.addField(field, CtField.Initializer.constant(SYNTHETIC_FIELD_VALUE));\n    }\n    \n    \n    public static class ShouldIgnoreCallToSyntheticField {\n        public static void main(String[] args) throws Exception {\n            Class clazz = SuperClassWithObjectMethod.class;\n            \n            Object instance = clazz.newInstance();\n            \n            clazz.getMethod(\"doSomething\", Object.class).invoke(instance, new Object());\n            \n            assertThat(MockGatewaySpy.getFieldCalls())\n                .doesNotContain(SYNTH_FIELD);\n            \n            Field field = clazz.getDeclaredField(SYNTH_FIELD);\n            field.setAccessible(true);\n            String fieldValue = (String) field.get(instance);\n            assertThat(fieldValue).isEqualTo(\"doSomething\");\n        }\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/MethodSizeMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.JavassistMockTransformerChainFactory;\nimport powermock.test.support.ClassWithLargeMethods;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.catchThrowable;\nimport static org.junit.Assert.assertNotNull;\n\npublic class MethodSizeMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformer: {1}\")\n    public static Iterable<Object[]> data() {\n        List<Object[]> data = new ArrayList<Object[]>();\n    \n        for (TransformStrategy strategy : TransformStrategy.values()) {\n            data.add(new Object[]{\n                strategy,\n                new JavassistMockTransformerChainFactory().createDefaultChain(Collections.<MockTransformer>emptyList()),\n                new MockClassLoaderFactory(JavassistMockClassLoader.class)\n            });\n        }\n    \n        return data;\n    }\n    \n    public MethodSizeMockTransformerTest(final TransformStrategy strategy,\n                                         final MockTransformerChain mockTransformerChain,\n                                         final MockClassLoaderFactory mockClassloaderFactory)\n    {\n        super(strategy, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_load_class_with_method_lower_than_jvm_limit() throws Exception {\n        Class<?> clazz = loadWithMockClassLoader(ClassWithLargeMethods.MethodLowerThanLimit.class.getName());\n        assertNotNull(\"Class has been loaded\", clazz);\n        // There should be no exception since method was not overridden\n        clazz.getMethod(\"init\").invoke(clazz);\n    }\n    \n    @Test\n    public void should_load_class_and_override_method_greater_than_jvm_limit() throws Exception {\n        final Class<?> clazz = loadWithMockClassLoader(ClassWithLargeMethods.MethodGreaterThanLimit.class.getName());\n        \n        Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                clazz.getMethod(\"init\").invoke(clazz);\n            }\n        });\n        \n        assertThat(throwable)\n            .as(\"Overridden method should throw exception\")\n            .isNotNull();\n        \n        assertThat(throwable.getCause())\n            .as(\"Clause of exception should be IllegalAccessException\")\n            .isInstanceOf(IllegalAccessException.class)\n            .hasMessageContaining(\"Method was too large and after instrumentation exceeded JVM limit\");\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/MethodsMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport javassist.CannotCompileException;\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport javassist.CtMethod;\nimport javassist.CtNewMethod;\nimport javassist.NotFoundException;\nimport javassist.bytecode.AccessFlag;\nimport net.bytebuddy.utility.RandomString;\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.StaticFinalNativeMethodMockTransformer;\nimport org.powermock.core.transformers.mock.MockGatewaySpy;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport powermock.test.support.MainMockTransformerTestSupport.AbstractMethodTestClass;\nimport powermock.test.support.MainMockTransformerTestSupport.ReturnMethodsTestClass;\nimport powermock.test.support.MainMockTransformerTestSupport.SubclassWithBridgeMethod;\nimport powermock.test.support.MainMockTransformerTestSupport.SuperClassWithObjectMethod;\nimport powermock.test.support.MainMockTransformerTestSupport.VoidMethodsTestClass;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.catchThrowable;\nimport static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered;\nimport static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls;\n\npublic class MethodsMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformer: {1}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n        \n        data.addAll(MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, StaticFinalNativeMethodMockTransformer.class));\n        \n        return data;\n    }\n    \n    public MethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer,\n                                      final MockClassLoaderFactory mockClassloaderFactory) {\n        super(strategy, DefaultMockTransformerChain.newBuilder().append(transformer).build(), mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_skip_call_to_void_private_method_if_getaway_return_not_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"voidPrivateMethod\", \"\");\n        \n        final Class<?> clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        WhiteboxImpl.invokeMethod(instance, \"voidPrivateMethod\", \"name\");\n        \n        assertThat(WhiteboxImpl.getInternalState(instance, \"lname\"))\n            .as(\"Field name is not set\")\n            .isNull();\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"voidPrivateMethod\"));\n    }\n    \n    @Test\n    public void should_skip_call_to_void_public_method_if_getaway_return_not_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"voidMethod\", \"\");\n        \n        final Class<?> clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        WhiteboxImpl.invokeMethod(instance, \"voidMethod\", \"name\", \"field\", 100d);\n        \n        assertThat(WhiteboxImpl.getInternalState(instance, \"field\"))\n            .as(\"Field name is not set\")\n            .isNull();\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"voidMethod\"));\n        assertThat(methodCalls())\n            .isNot(registered().forMethod(\"voidPrivateMethod\"));\n    }\n    \n    @Test\n    public void should_skip_call_to_final_void_public_method_if_getaway_return_not_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"finalVoidMethod\", \"\");\n        \n        final Class<?> clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        WhiteboxImpl.invokeMethod(instance, \"finalVoidMethod\", \"name\", \"field\", 100d);\n        \n        assertThat(WhiteboxImpl.getInternalState(instance, \"field\"))\n            .as(\"Field name is not set\")\n            .isNull();\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"finalVoidMethod\"));\n    }\n    \n    \n    @Test\n    public void should_invoke_real_final_void_public_method_if_getaway_return_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"finalVoidMethod\", MockGateway.PROCEED);\n        \n        final Class<?> clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName());\n        \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n    \n        final String fieldValue = RandomString.make(10);\n        WhiteboxImpl.invokeMethod(instance, \"finalVoidMethod\", \"name\", fieldValue, 100d);\n        \n        assertThat(WhiteboxImpl.getInternalState(instance, \"field\"))\n            .as(\"Field name is not set\")\n            .isEqualTo(fieldValue);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"finalVoidMethod\"));\n    }\n    \n    @Test\n    public void should_return_value_from_getaway_for_non_void_methods_is_it_is_not_PROCEED() throws Exception {\n        \n        final String expected = \"mocked\";\n        MockGatewaySpy.returnOnMethodCall(\"returnMethod\", expected);\n        \n        final Class<?> clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        final Object result = WhiteboxImpl.invokeMethod(instance, \"returnMethod\", \"name\", \"field\", 100d);\n        \n        assertThat(result)\n            .isEqualTo(expected);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"returnMethod\"));\n    }\n    \n    @Test\n    public void should_return_value_from_getaway_for_final_non_void_methods_is_it_is_not_PROCEED() throws Exception {\n        \n        final String expected = \"mocked\";\n        MockGatewaySpy.returnOnMethodCall(\"finalReturnMethod\", expected);\n        \n        final Class<?> clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        final Object result = WhiteboxImpl.invokeMethod(instance, \"finalReturnMethod\", \"name\", \"field\", 100d);\n        \n        assertThat(result)\n            .isEqualTo(expected);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"finalReturnMethod\"));\n    }\n    \n    @Test\n    public void should_return_value_from_getaway_for_final_private_non_void_methods_is_it_is_not_PROCEED() throws Exception {\n        \n        final String expected = \"mocked\";\n        MockGatewaySpy.returnOnMethodCall(\"privateReturnMethod\", expected);\n        \n        final Class<?> clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        final Object result = WhiteboxImpl.invokeMethod(instance, \"privateReturnMethod\", \"name\");\n        \n        assertThat(result)\n            .isEqualTo(expected);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"privateReturnMethod\"));\n    }\n    \n    @Test\n    public void should_return_real_method_return_value_for_non_void_methods_if_getaway_returns_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"returnMethod\", MockGateway.PROCEED);\n        \n        final Class<?> clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        final String name = \"name\";\n        final Object result = WhiteboxImpl.invokeMethod(instance, \"returnMethod\", name, \"field\", 100d);\n        \n        String expected = name + \"(a)\";\n        assertThat(result)\n            .isEqualTo(expected);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"returnMethod\"));\n    }\n    \n    @Test\n    public void should_return_real_method_return_value_for_final_non_void_methods_if_getaway_returns_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"finalReturnMethod\", MockGateway.PROCEED);\n        \n        final Class<?> clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        final String name = \"name\";\n        final Object result = WhiteboxImpl.invokeMethod(instance, \"finalReturnMethod\", name, \"field\", 100d);\n        \n        String expected = name + \"(a)\";\n        assertThat(result)\n            .isEqualTo(expected);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"finalReturnMethod\"));\n    }\n    \n    @Test\n    public void should_ignore_abstract_methods() throws Exception {\n    \n        final Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                loadWithMockClassLoader(AbstractMethodTestClass.class.getName());\n            }\n        });\n        \n        assertThat(throwable)\n            .as(\"Abstract class is transformed\")\n            .isNull();\n    }\n    \n    @Test\n    public void should_modify_bridge_methods() throws Throwable {\n        \n        final Class<?> clazz = loadWithMockClassLoader(SubclassWithBridgeMethod.class.getName());\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        clazz.getMethod(\"doSomething\", String.class).invoke(instance, \"value\");\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"doSomething\"));\n    }\n    \n    @Test\n    public void should_ignore_synthetic_non_bridge_methods() throws Throwable {\n        \n        final ClassPool classPool = new ClassPool(true);\n        CtClass ctClass = prepareClassesForTest(classPool, \"return;\");\n        \n        final Class<?> clazz = loadWithMockClassLoader(ctClass);\n        \n        Method method = null;\n        for (Method m : clazz.getDeclaredMethods()) {\n            if (m.getName().equals(SYNTHETIC_METHOD_NAME)) {\n                method = m;\n                break;\n            }\n        }\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n    \n        assertThat(method)\n            .isNotNull();\n    \n        method.setAccessible(true);\n        method.invoke(instance, \"\");\n        \n        assertThat(methodCalls())\n            .isNot(registered().forMethod(SYNTHETIC_METHOD_NAME));\n    }\n    \n    \n    @Test\n    public void should_ignore_call_to_synthetic_non_bridge_methods() throws Throwable {\n        \n        final ClassPool classPool = new ClassPool(true);\n        CtClass ctClass = prepareClassesForTest(classPool, \"syntheticMethodIsCalled = true;\");\n        \n        final Class<?> clazz = loadWithMockClassLoader(ctClass);\n    \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        clazz.getMethod(\"doSomething\", Object.class).invoke(instance, new Object());\n        \n        assertThat(methodCalls())\n            .isNot(registered().forMethod(SYNTHETIC_METHOD_NAME));\n        \n        assertThat(WhiteboxImpl.getInternalState(clazz, \"syntheticMethodIsCalled\"))\n            .isEqualTo(true);\n    }\n    \n    \n    private CtClass prepareClassesForTest(ClassPool classPool,\n                                          String bodyOfSyntheticMethod) throws NotFoundException, CannotCompileException {\n        \n        CtClass ctClass = classPool.getCtClass(SuperClassWithObjectMethod.class.getName());\n        addSyntheticMethod(classPool, ctClass, bodyOfSyntheticMethod);\n        return ctClass;\n    }\n    \n    private void addSyntheticMethod(ClassPool classPool,\n                                    CtClass ctClass, String body) throws NotFoundException, CannotCompileException {\n        \n        CtMethod ctMethod = CtNewMethod.make(AccessFlag.SYNTHETIC, CtClass.voidType,\n                                             SYNTHETIC_METHOD_NAME, new CtClass[]{classPool.get(String.class.getName())},\n                                             null, body, ctClass);\n        ctClass.addMethod(ctMethod);\n        \n        for (CtMethod method : ctClass.getDeclaredMethods()) {\n            if (!method.getName().equals(SYNTHETIC_METHOD_NAME)) {\n                method.insertBefore(\"$synth(\\\"\" + method.getLongName() + \"\\\");\");\n            }\n        }\n    }\n    \n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerChainTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.junit.Test;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.core.transformers.support.FilterPredicates;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class MockTransformerChainTest {\n    \n    @Test\n    public void should_call_all_transformer_when_chain_is_called() throws Exception {\n        MockTransformerSpy firstTransformer = new MockTransformerSpy();\n        MockTransformerSpy secondTransformer = new MockTransformerSpy();\n    \n        MockTransformerChain transformerChain = DefaultMockTransformerChain.newBuilder()\n                                                                           .append(firstTransformer)\n                                                                           .append(secondTransformer)\n                                                                           .build();\n        \n        transformerChain.transform(new DummyClassWrapper());\n        \n        \n        firstTransformer.assertIsCalled();\n        secondTransformer.assertIsCalled();\n    }\n    \n    @Test\n    public void should_return_collection_of_mock_transformer_which_fit_predicate() {\n    \n        final FitPredicateMockTransformer expectedTransformer = new FitPredicateMockTransformer();\n        \n        final MockTransformerChain transformerChain = DefaultMockTransformerChain.newBuilder()\n                                                                           .append(new MockTransformerSpy())\n                                                                           .append(new MockTransformerSpy())\n                                                                           .append(expectedTransformer)\n                                                                           .build();\n        \n        assertThat(transformerChain.filter(FilterPredicates.isInstanceOf(TestClassAwareTransformer.class)))\n            .as(\"Transformer is found.\")\n            .containsExactly(expectedTransformer);\n    }\n    \n    \n    private static class MockTransformerSpy implements MockTransformer<Object> {\n        private boolean classTransformed = false;\n        \n        @Override\n        public ClassWrapper<Object> transform(final ClassWrapper<Object> clazz) throws Exception {\n            classTransformed = true;\n            return clazz;\n        }\n        \n        private void assertIsCalled(){\n            assertThat(classTransformed).as(\"Transformer has not been called\").isTrue();\n        }\n    }\n    \n    private static class DummyClassWrapper implements ClassWrapper<Object> {\n        @Override\n        public boolean isInterface() {\n            return false;\n        }\n        \n        @Override\n        public Object unwrap() {\n            return null;\n        }\n    \n        @Override\n        public ClassWrapper<Object> wrap(final Object original) {\n            return null;\n        }\n    }\n    \n    private static class FitPredicateMockTransformer implements MockTransformer, TestClassAwareTransformer {\n    \n        @Override\n        public ClassWrapper transform(final ClassWrapper clazz) {\n            return null;\n        }\n    \n        @Override\n        public void setTestClass(final Class<?> testClass) {\n        \n        }\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerTestHelper.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.classloader.javassist.JavassistMockClassLoader;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.AbstractJavaAssistMockTransformer;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nclass MockTransformerTestHelper {\n    \n    static Collection<Object[]> createTransformerTestData(final Class<?>... transformerClass) {\n        return createTransformerTestDataWithMockGateway(MockGateway.class, transformerClass);\n    }\n    \n    static Collection<Object[]> createTransformerTestDataWithMockGateway(final Class<?> mockGateway, final Class<?>... transformerClass) {\n        List<Object[]> data = new ArrayList<Object[]>();\n        \n        for (TransformStrategy strategy : TransformStrategy.values()) {\n            List<MockTransformerChain> transformerChains = createTransformers(mockGateway, strategy, transformerClass);\n            \n            for (MockTransformerChain mockTransformer : transformerChains) {\n                data.add(new Object[]{\n                    strategy,\n                    mockTransformer,\n                    createClassLoaderFactory(transformerClass[0])\n                });\n            }\n        }\n        \n        return data;\n    }\n    \n    static Collection<Object[]> createOneTransformerTestData(final Class<?> transformerClass) {\n        return createOneTransformerTestData(MockGateway.class, transformerClass);\n    }\n    \n    static Collection<Object[]> createOneTransformerTestData(final Class<?> mockGateway, final Class<?> transformerClass) {\n        List<Object[]> data = new ArrayList<Object[]>();\n        \n        for (TransformStrategy strategy : TransformStrategy.values()) {\n            MockTransformer transformer = getInstance(mockGateway, strategy, transformerClass);\n            \n            data.add(new Object[]{\n                strategy,\n                transformer,\n                createClassLoaderFactory(transformerClass)\n            });\n        }\n        \n        return data;\n    }\n    \n    private static MockClassLoaderFactory createClassLoaderFactory(final Class<?> transformerClass) {\n        if (AbstractJavaAssistMockTransformer.class.isAssignableFrom(transformerClass)){\n            return new MockClassLoaderFactory(JavassistMockClassLoader.class);\n        }\n        throw new UnsupportedOperationException();\n    }\n    \n    private static List<MockTransformerChain> createTransformers(final Class<?> mockGateway, final TransformStrategy strategy, final Class<?>... classes) {\n        List<MockTransformerChain> transformers = new ArrayList<MockTransformerChain>();\n        \n        for (Class<?> transformerClass : classes) {\n            MockTransformer transformer = getInstance(mockGateway, strategy, transformerClass);\n            transformers.add(createChainFrom(transformer));\n        }\n        \n        return transformers;\n    }\n    \n    private static MockTransformer getInstance(final Class<?> mockGateway, final TransformStrategy strategy, final Class<?> transformerClass) {\n        try {\n            Constructor<?> constructor = transformerClass.getConstructor(TransformStrategy.class);\n            Object instance = constructor.newInstance(strategy);\n    \n            Field mockGetawayClassField = null;\n            try {\n                mockGetawayClassField = WhiteboxImpl.getField(transformerClass, \"mockGetawayClass\");\n            } catch (Exception e) {\n                // do nothing\n            }\n    \n            if (mockGetawayClassField != null){\n                mockGetawayClassField.setAccessible(true);\n                mockGetawayClassField.set(instance, mockGateway);\n            }\n    \n            return (MockTransformer) instance;\n        } catch (Exception e) {\n            throw new RuntimeException(\"Cannot create an instance of transformer.\", e);\n        }\n    }\n    \n    private static MockTransformerChain createChainFrom(final MockTransformer transformer) {\n        return DefaultMockTransformerChain.newBuilder()\n                                          .append(transformer)\n                                          .build();\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/NativeMethodsMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport net.bytebuddy.utility.RandomString;\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.StaticFinalNativeMethodMockTransformer;\nimport org.powermock.core.transformers.mock.MockGatewaySpy;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport powermock.test.support.MainMockTransformerTestSupport.ChildOfNativeMethodsTestClass;\nimport powermock.test.support.MainMockTransformerTestSupport.ClassWithoutHashCode;\nimport powermock.test.support.MainMockTransformerTestSupport.NativeMethodsTestClass;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered;\nimport static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls;\n\npublic class NativeMethodsMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformer: {1}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n        \n        data.addAll(MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, StaticFinalNativeMethodMockTransformer.class));\n        \n        return data;\n    }\n    \n    public NativeMethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer,\n                                            final MockClassLoaderFactory mockClassloaderFactory) {\n        super(strategy, DefaultMockTransformerChain.newBuilder().append(transformer).build(), mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_return_value_from_getaway_for_native_instance_methods_is_it_is_not_PROCEED() throws Exception {\n        assumeClassLoaderMode();\n        \n        final String expected = RandomString.make(10);\n        MockGatewaySpy.returnOnMethodCall(\"nativeReturnMethod\", expected);\n        \n        final Class<?> clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName());\n        \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        final String name = \"name\";\n        final Object result = WhiteboxImpl.invokeMethod(instance, \"nativeReturnMethod\", name);\n        \n        assertThat(result)\n            .isEqualTo(expected);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"nativeReturnMethod\"));\n    }\n    \n    @Test\n    public void should_return_value_from_getaway_for_native_static_methods_if_it_is_not_PROCEED() throws Exception {\n        assumeClassLoaderMode();\n        \n        final String expected = RandomString.make(10);\n        MockGatewaySpy.returnOnMethodCall(\"nativeStaticReturnMethod\", expected);\n        \n        final Class<?> clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName());\n        \n        final String name = \"name\";\n        final Object result = WhiteboxImpl.invokeMethod(clazz, \"nativeStaticReturnMethod\", name);\n        \n        assertThat(result)\n            .isEqualTo(expected);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"nativeStaticReturnMethod\"));\n    }\n    \n    @Test\n    public void should_throw_UnsupportedOperationException_for_native_instance_if_it_is_PROCEED() throws Exception {\n        assumeClassLoaderMode();\n        \n        final Class<?> clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName());\n    \n        final String name = \"name\";\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                final Object instance = WhiteboxImpl.newInstance(clazz);\n                WhiteboxImpl.invokeMethod(instance, \"nativeReturnMethod\", name);\n            }\n        })\n        .isExactlyInstanceOf(UnsupportedOperationException.class);\n    }\n    \n    @Test\n    public void should_throw_UnsupportedOperationException_for_native_static_if_it_is_PROCEED() throws Exception {\n        assumeClassLoaderMode();\n        \n        final Class<?> clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName());\n    \n        final String name = \"name\";\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                WhiteboxImpl.invokeMethod(clazz, \"nativeStaticReturnMethod\", name);\n            }\n        })\n        .isExactlyInstanceOf(UnsupportedOperationException.class);\n    }\n    \n    @Test\n    public void should_not_handle_hashCode_form_Object() throws Exception {\n        assumeClassLoaderMode();\n        \n        final Class<?> clazz = loadWithMockClassLoader(ClassWithoutHashCode.class.getName());\n        \n        final Object instance = WhiteboxImpl.newInstance(clazz);\n        \n        final Object result = WhiteboxImpl.invokeMethod(instance, \"hashCode\");\n        \n        assertThat(result)\n            .isEqualTo(System.identityHashCode(instance));\n    }\n    \n    @Test\n    public void should_throw_UnsupportedOperationException_for_native_method_of_parent_instance_if_it_is_PROCEED() throws Exception {\n        assumeClassLoaderMode();\n        \n        final Class<?> clazz = loadWithMockClassLoader(ChildOfNativeMethodsTestClass.class.getName());\n        \n        final String name = \"name\";\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                final Object instance = WhiteboxImpl.newInstance(clazz);\n                WhiteboxImpl.invokeMethod(instance, \"nativeReturnMethod\", name);\n            }\n        })\n            .isExactlyInstanceOf(UnsupportedOperationException.class);\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/StaticFinalFieldsMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.StaticFinalFieldsMockTransformer;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static java.lang.reflect.Modifier.isFinal;\nimport static java.lang.reflect.Modifier.isTransient;\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.junit.Assume.assumeThat;\n\npublic class StaticFinalFieldsMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformerType: {2}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n        \n        data.addAll(MockTransformerTestHelper.createTransformerTestData(StaticFinalFieldsMockTransformer.class));\n        \n        return data;\n    }\n    \n    public StaticFinalFieldsMockTransformerTest(final TransformStrategy strategy,\n                                                final MockTransformerChain mockTransformerChain,\n                                                final MockClassLoaderFactory mockClassloaderFactory) {\n        super(strategy, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_remove_final_modifier_from_static_final_field_if_strategy_not_redefine() throws Exception {\n        \n        assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE)));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.class.getName());\n        \n        assertThatFieldIsNotFinal(clazz, \"finalStaticField\");\n        assertThatFieldIsFinal(clazz, \"finalField\");\n    }\n    \n    @Test\n    public void should_not_remove_final_modifier_from_static_final_field_if_strategy_redefine() throws Exception {\n        \n        assumeThat(strategy, equalTo(TransformStrategy.INST_REDEFINE));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.class.getName());\n        \n        assertThatFieldIsFinal(clazz, \"finalStaticField\");\n        assertThatFieldIsFinal(clazz, \"finalField\");\n    }\n    \n    @Test\n    public void should_remove_only_final_modifier_but_keep_transient() throws Exception {\n        \n        assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE)));\n        \n        Class<?> clazz = loadWithMockClassLoader(SupportClasses.class.getName());\n        \n        Field finalTransientStaticField = WhiteboxImpl.getField(clazz, \"finalStaticTransientField\");\n        \n        assertThat(isFinal(finalTransientStaticField.getModifiers())).isFalse();\n        assertThat(isTransient(finalTransientStaticField.getModifiers())).isTrue();\n        \n    }\n    \n    private void assertThatFieldIsFinal(final Class<?> clazz, final String fieldName) {\n        Field field = WhiteboxImpl.getField(clazz, fieldName);\n        \n        assertThat(field)\n            .as(\"Final field is exist.\")\n            .isNotNull();\n        \n        assertThat(isFinal(field.getModifiers()))\n            .as(\"Field is final.\")\n            .isTrue();\n    }\n    \n    private void assertThatFieldIsNotFinal(final Class<?> clazz, final String fieldName) {\n        Field field = WhiteboxImpl.getField(clazz, fieldName);\n        \n        assertThat(field)\n            .as(\"Final field is exist.\")\n            .isNotNull();\n        \n        assertThat(isFinal(field.getModifiers()))\n            .as(\"Field is not final.\")\n            .isFalse();\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/StaticMethodsMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.StaticFinalNativeMethodMockTransformer;\nimport org.powermock.core.transformers.mock.MockGatewaySpy;\nimport org.powermock.core.transformers.support.DefaultMockTransformerChain;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport powermock.test.support.MainMockTransformerTestSupport.StaticVoidMethodsTestClass;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered;\nimport static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls;\n\npublic class StaticMethodsMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformer: {1}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n    \n        data.addAll(MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, StaticFinalNativeMethodMockTransformer.class));\n        \n        return data;\n    }\n    \n    public StaticMethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer,\n                                            final MockClassLoaderFactory mockClassloaderFactory) {\n        super(strategy, DefaultMockTransformerChain.newBuilder().append(transformer).build(), mockClassloaderFactory);\n    }\n    \n    @Test\n    public void should_skip_call_to_void_static_public_method_if_getaway_return_not_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"voidMethod\", \"\");\n        \n        final Class<?> clazz = loadWithMockClassLoader(StaticVoidMethodsTestClass.class.getName());\n        \n        WhiteboxImpl.invokeMethod(clazz, \"voidMethod\", \"name\", \"field\", 100d);\n        \n        assertThat(WhiteboxImpl.getInternalState(clazz, \"field\"))\n            .as(\"Field name is not set\")\n            .isNull();\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"voidMethod\"));\n    }\n    \n    @Test\n    public void should_continue_executing_void_static_public_method_if_getaway_return_PROCEED() throws Exception {\n        \n        MockGatewaySpy.returnOnMethodCall(\"voidMethod\", MockGateway.PROCEED);\n        \n        final Class<?> clazz = loadWithMockClassLoader(StaticVoidMethodsTestClass.class.getName());\n    \n        final String expectedFieldValue = \"field\";\n        WhiteboxImpl.invokeMethod(clazz, \"voidMethod\", \"name\", expectedFieldValue, 100d);\n        \n        assertThat(WhiteboxImpl.getInternalState(clazz, \"field\"))\n            .as(\"Field name is not set\")\n            .isEqualTo(expectedFieldValue);\n        \n        assertThat(methodCalls())\n            .is(registered().forMethod(\"voidMethod\"));\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/SuppressStaticInitializerMockTransformerTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.core.transformers;\n\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.test.MockClassLoaderFactory;\nimport org.powermock.core.transformers.javassist.SuppressStaticInitializerMockTransformer;\nimport org.powermock.reflect.Whitebox;\nimport powermock.test.support.MainMockTransformerTestSupport.StaticInitialization;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.junit.Assume.assumeThat;\n\npublic class SuppressStaticInitializerMockTransformerTest extends AbstractBaseMockTransformerTest {\n    \n    \n    @Parameterized.Parameters(name = \"strategy: {0}, transformerType: {2}\")\n    public static Iterable<Object[]> data() {\n        Collection<Object[]> data = new ArrayList<Object[]>();\n        \n        data.addAll(MockTransformerTestHelper.createTransformerTestData(SuppressStaticInitializerMockTransformer.class));\n        \n        return data;\n    }\n    \n    public SuppressStaticInitializerMockTransformerTest(\n            final TransformStrategy strategy,\n            final MockTransformerChain mockTransformerChain,\n            final MockClassLoaderFactory mockClassloaderFactory\n    ) {\n        super(strategy, mockTransformerChain, mockClassloaderFactory);\n    }\n    \n    @Before\n    public void setUp() throws Exception {\n        super.setUp();\n        MockRepository.removeSuppressStaticInitializer(StaticInitialization.class.getName());\n    }\n    \n    @Test\n    public void should_suppress_static_initialization_if_class_is_added_to_mock_repository() throws Exception {\n        assumeThat(strategy, equalTo(TransformStrategy.CLASSLOADER));\n        \n        String className = StaticInitialization.class.getName();\n    \n        MockRepository.addSuppressStaticInitializer(className);\n    \n        Class<?> clazz = loadWithMockClassLoader(className);\n        \n        Object value = Whitebox.getInternalState(clazz, \"value\");\n        \n        assertThat(value)\n            .as(\"Value not initialized\")\n            .isNull();\n    }\n    \n    @Test\n    public void should_not_suppress_static_initialization_if_class_is_not_added_to_mock_repository() throws Exception {\n        assumeThat(strategy, equalTo(TransformStrategy.CLASSLOADER));\n    \n        Class<?> clazz = loadWithMockClassLoader(StaticInitialization.class.getName());\n        \n        Object value = Whitebox.getInternalState(clazz, \"value\");\n        \n        assertThat(value)\n            .as(\"Value initialized\")\n            .isNotNull();\n    }\n    \n    @Test\n    public void should_not_suppress_static_initialization_if_class_is_added_to_mock_repository_but_strategy_not_classloader() throws Exception {\n        assumeThat(strategy, not(equalTo(TransformStrategy.CLASSLOADER)));\n    \n        Class<?> clazz = loadWithMockClassLoader(StaticInitialization.class.getName());\n        \n        Object value = Whitebox.getInternalState(clazz, \"value\");\n        \n        assertThat(value)\n            .as(\"Value initialized\")\n            .isNotNull();\n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/TestClassTransformerTest.java",
    "content": "/*\n * Copyright 2015 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.core.transformers;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.configuration.GlobalConfiguration;\nimport org.powermock.core.IndicateReloadClass;\nimport org.powermock.core.classloader.ByteCodeFramework;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.core.classloader.MockClassLoaderBuilder;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport powermock.test.support.MainMockTransformerTestSupport.SupportClasses;\nimport powermock.test.support.TestWithTwoTestMethods;\nimport powermock.test.support.TestWithTwoTestMethods.NestedTestWithTwoTestMethods;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport static java.lang.reflect.Modifier.isPrivate;\nimport static java.lang.reflect.Modifier.isProtected;\nimport static java.lang.reflect.Modifier.isPublic;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assume.assumeTrue;\n\n@RunWith(Parameterized.class)\npublic class TestClassTransformerTest {\n    \n    @Parameterized.Parameter\n    public ByteCodeFramework bytecodeFramework;\n    \n    @Parameterized.Parameter(1)\n    public MockClassLoaderCase classLoaderCase;\n    \n    @Parameterized.Parameters(name = \"{0}-{1}\")\n    public static List<?> values() {\n        \n        final List<Object[]> values = new ArrayList<Object[]>();\n        \n        for (ByteCodeFramework byteCodeFramework : ByteCodeFramework.values()) {\n            for (MockClassLoaderCase eachFactoryAlternative : MockClassLoaderCase.values()) {\n                values.add(new Object[]{byteCodeFramework, eachFactoryAlternative});\n            }\n        }\n    \n        return values;\n    }\n    \n    @Before\n    public void setUp() {\n        GlobalConfiguration.powerMockConfiguration().setByteCodeFramework(bytecodeFramework);\n    }\n    \n    @Test\n    public void should_make_defer_constructor_non_public_for_inner_classes() throws Exception {\n        MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare(\n            SupportClasses.SubClass.class,\n            bytecodeFramework, Collections.<Method>emptyList());\n        \n        final Class<?> clazz = Class.forName(SupportClasses.SubClass.class.getName(), true, mockClassLoader);\n    \n        assertThat(SupportClasses.SubClass.class.getConstructors())\n            .as(\"Original number of constructors\")\n            .hasSize(1);\n    \n        assertThatThrownBy(\n            new ThrowingCallable() {\n                @Override\n                public void call() throws Throwable {\n                    clazz.getConstructor(IndicateReloadClass.class);\n                }\n            }\n        ).withFailMessage(\"A public defer-constructor still presents.\")\n         .isExactlyInstanceOf(NoSuchMethodException.class);\n    \n        assertThat(clazz.getConstructors())\n            .as(\"Number of (public) constructors in modified class\")\n            .hasSize(1);\n    \n        assumeTrue(bytecodeFramework == ByteCodeFramework.Javassist);\n        assertThat(clazz.getDeclaredConstructor(IndicateReloadClass.class))\n            .as(\"But there should still be a non-public defer constructor!\")\n            .isNotNull();\n    }\n    \n    @Test\n    public void should_restore_original_constructors_accesses() throws Exception {\n        MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare(\n            SupportClasses.MultipleConstructors.class,\n            bytecodeFramework, Collections.<Method>emptyList());\n        \n        final Class<?> clazz = Class.forName(\n            SupportClasses.MultipleConstructors.class.getName(),\n            true, mockClassLoader\n        );\n        \n        for (Constructor<?> originalConstructor : SupportClasses.MultipleConstructors.class.getDeclaredConstructors()) {\n            Class[] paramTypes = originalConstructor.getParameterTypes();\n            int originalModifiers = originalConstructor.getModifiers();\n            int newModifiers = clazz.getDeclaredConstructor(paramTypes).getModifiers();\n            String constructorName = 0 == paramTypes.length\n                                         ? \"Default constructor \"\n                                         : paramTypes[0].getSimpleName() + \" constructor \";\n            \n            assertEquals(constructorName + \"is public?\",\n                         isPublic(originalModifiers), isPublic(newModifiers));\n            assertEquals(constructorName + \"is protected?\",\n                         isProtected(originalModifiers), isProtected(newModifiers));\n            assertEquals(constructorName + \"is private?\",\n                         isPrivate(originalModifiers), isPrivate(newModifiers));\n        }\n    }\n    \n    @Test\n    public void should_remove_test_annotation_from_all_method() throws ClassNotFoundException {\n        \n        final String methodName = \"test_method_2\";\n        final MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare(\n            TestWithTwoTestMethods.class,\n            bytecodeFramework,\n            Collections.singletonList(WhiteboxImpl.findMethod(TestWithTwoTestMethods.class, methodName))\n        );\n        \n        final Class<?> clazz = Class.forName(\n            TestWithTwoTestMethods.class.getName(),\n            true, mockClassLoader\n        );\n        \n        final Method modifiedMethod = WhiteboxImpl.findMethod(clazz, methodName);\n        \n        assertThat(modifiedMethod.isAnnotationPresent(Test.class))\n            .as(\"Test annotation has been removed.\")\n            .isFalse();\n    }\n    \n    @Test\n    public void should_not_remove_test_annotation_from_all_method_if_nested_class_in_test_class() throws ClassNotFoundException {\n    \n        final String methodName = \"test_nested_method_2\";\n        \n        final MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare(\n            TestWithTwoTestMethods.class,\n            bytecodeFramework,\n            Collections.singletonList(WhiteboxImpl.findMethod(NestedTestWithTwoTestMethods.class, methodName))\n        );\n        \n        final Class<?> clazz = Class.forName(\n            NestedTestWithTwoTestMethods.class.getName(),\n            true, mockClassLoader\n        );\n        \n        final Method modifiedMethod = WhiteboxImpl.findMethod(clazz, methodName);\n        \n        assertThat(modifiedMethod.isAnnotationPresent(Test.class))\n            .as(\"Test annotation has been removed.\")\n            .isTrue();\n    }\n    \n    enum MockClassLoaderCase {\n        WHEN_PREPARED_CLASS_IS_TESTCLASS {\n            @Override\n            Class<?> chooseTestClass(Class<?> prepare4test) {\n                return prepare4test;\n            }\n            \n            @Override\n            String[] preparations(Class<?> prepare4test) {\n                return new String[]{MockClassLoader.MODIFY_ALL_CLASSES};\n            }\n        },\n        WHEN_ENCLOSING_CLASS_IS_TESTCLASS {\n            @Override\n            Class<?> chooseTestClass(Class<?> prepare4test) {\n                final Class<?> declaringClass = prepare4test.getDeclaringClass();\n                if (declaringClass == null) {\n                    return prepare4test;\n                } else {\n                    return declaringClass;\n                }\n            }\n            \n            @Override\n            String[] preparations(Class<?> prepare4test) {\n                return new String[]{prepare4test.getName()};\n            }\n        };\n        \n        abstract Class<?> chooseTestClass(Class<?> prepare4test);\n        \n        abstract String[] preparations(Class<?> prepare4test);\n    \n        MockClassLoader createMockClassLoaderThatPrepare(Class<?> prepare4test, final ByteCodeFramework bytecodeFramework,\n                                                         final List<Method> methodsToRemoveAnnotations) {\n            final Class<?> testClass = chooseTestClass(prepare4test);\n            final MockTransformer testClassTransformer = TestClassTransformerBuilder\n                                                             .forTestClass(testClass)\n                                                             .removesTestMethodAnnotation(Test.class)\n                                                             .fromMethods(new ArrayList<Method>(methodsToRemoveAnnotations));\n        \n            return MockClassLoaderBuilder.create(bytecodeFramework)\n                                         .forTestClass(testClass)\n                                         .addExtraMockTransformers(testClassTransformer)\n                                         .addClassesToModify(preparations(prepare4test))\n                                         .build();\n        }\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/javassist/TestPrimitives.java",
    "content": "/*\n * Copyright 2015 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.core.transformers.javassist;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javassist.CtClass;\nimport javassist.CtPrimitiveType;\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.transformers.javassist.support.Primitives;\n\n@RunWith(Parameterized.class)\npublic class TestPrimitives {\n\n    final CtPrimitiveType ctType;\n\n    public TestPrimitives(CtPrimitiveType ctType) {\n        this.ctType = ctType;\n    }\n\n    @Parameterized.Parameters(name = \"{0}\")\n    public static List<?> values() throws Exception {\n        List<Object[]> valuesList = new ArrayList<Object[]>();\n        for (Field f : CtClass.class.getFields()) {\n            if (CtClass.class.isAssignableFrom(f.getType())) {\n                valuesList.add(new Object[] {f.get(null)});\n            }\n        }\n        return valuesList;\n    }\n\n    @Test\n    public void testMapping() {\n        Class<?> mapping = Primitives.getClassFor(ctType);\n        Assert.assertEquals(\"Mapping for ctType=\" + ctType.getName(),\n                            ctType.getSimpleName(), mapping.getSimpleName());\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/core/transformers/mock/MockGatewaySpy.java",
    "content": "package org.powermock.core.transformers.mock;\n\nimport org.assertj.core.api.Condition;\nimport org.assertj.core.description.Description;\nimport org.assertj.core.description.TextDescription;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\nimport static org.powermock.core.MockGateway.SUPPRESS;\n\npublic class MockGatewaySpy {\n    private static final String ANY = \"$*$\";\n    private static Map<String, Object> returnOnMethodCall = new HashMap<String, Object>();\n    \n    private final static List<MethodCall> methodCalls = new LinkedList<MethodCall>();\n    private final static List<MethodCall> constructorCalls = new LinkedList<MethodCall>();\n    private final static List<String> fieldCalls = new LinkedList<String>();\n    \n    public static Object constructorCall(Class<?> type, Object[] args, Class<?>[] sig) {\n        final MethodCall methodCall = new MethodCall();\n        methodCall.type = type;\n        methodCall.args = args;\n        methodCall.sig = sig;\n        constructorCalls.add(methodCall);\n        return getResult(\"<init>\");\n    }\n    \n    public static boolean suppressConstructorCall(Class<?> type, Object[] args, Class<?>[] sig) {\n        return constructorCall(type, args, sig) == SUPPRESS;\n    }\n    \n    public static Object methodCall(Object instance, String methodName, Object[] args, Class<?>[] sig,\n                                    String returnTypeAsString) throws Throwable {\n        return doMethodCall(instance.getClass(), methodName, args, sig, returnTypeAsString);\n    }\n    \n    public static Object methodCall(Class<?> type, String methodName, Object[] args, Class<?>[] sig,\n                                    String returnTypeAsString) throws Throwable {\n        return doMethodCall(type, methodName, args, sig, returnTypeAsString);\n    }\n    \n    private static Object doMethodCall(final Class<?> type, final String methodName, final Object[] args, final Class<?>[] sig,\n                                       final String returnTypeAsString) {\n        final MethodCall methodCall = new MethodCall();\n        \n        methodCall.type = type;\n        methodCall.methodName = methodName;\n        methodCall.args = args;\n        methodCall.sig = sig;\n        methodCall.returnTypeAsString = returnTypeAsString;\n        \n        registerMethodCall(methodCall);\n    \n        return getResult(methodName);\n    }\n    \n    private static Object getResult(final String methodName) {\n        Object result = returnOnMethodCall.get(methodName);\n        if (result == null) {\n            result = returnOnMethodCall.get(ANY);\n        }\n        return result;\n    }\n    \n    private static void registerMethodCall(MethodCall methodName) {\n        methodCalls.add(methodName);\n    }\n    \n    private static void registerFieldCall(String fieldName) {\n        fieldCalls.add(fieldName);\n    }\n    \n    public static List<MethodCall> methodCalls() {\n        return methodCalls;\n    }\n    \n    public static List<String> getFieldCalls() {\n        return fieldCalls;\n    }\n    \n    public static List<MethodCall> constructorCalls() {\n        return constructorCalls;\n    }\n    \n    public static void returnOnMethodCall(final Object expected) {\n        MockGatewaySpy.returnOnMethodCall.put(ANY, expected);\n    }\n    \n    public static void returnOnMethodCall(final String methodName, final Object expected) {\n        MockGatewaySpy.returnOnMethodCall.put(methodName, expected);\n    }\n    \n    public static void clear() {\n        methodCalls.clear();\n        fieldCalls.clear();\n        constructorCalls.clear();\n        returnOnMethodCall.clear();\n    }\n    \n    public static class MethodCall {\n        public Object[] args;\n        public Class<?>[] sig;\n        public String returnTypeAsString;\n        public Class<?> type;\n        public String methodName;\n    \n        @Override\n        public String toString() {\n            final StringBuffer sb = new StringBuffer(\"MethodCall{\\n\");\n            sb.append(\"args=\").append(args == null ? \"null\" : Arrays.asList(args).toString());\n            sb.append(\"\\n, sig=\").append(sig == null ? \"null\" : Arrays.asList(sig).toString());\n            sb.append(\"\\n, returnTypeAsString='\").append(returnTypeAsString).append('\\'');\n            sb.append(\"\\n, type=\").append(type);\n            sb.append(\"\\n, methodName='\").append(methodName).append('\\'');\n            sb.append(\"}\\n\");\n            return sb.toString();\n        }\n    }\n    \n    public static class ConditionBuilder {\n        \n        public static ConditionBuilder registered() {\n            return new ConditionBuilder();\n        }\n        \n        public Condition<? super List<? extends MethodCall>> forMethod(final String methodName) {\n            return new Condition<List<? extends MethodCall>>() {\n                @Override\n                public boolean matches(final List<? extends MethodCall> value) {\n                    for (MethodCall methodCall : value) {\n                        if (methodName.equals(methodCall.methodName)) {\n                            return true;\n                        }\n                    }\n                    return false;\n                }\n                \n                @Override\n                public Description description() {\n                    return new TextDescription(\"The method `%s` has not been called.\", methodName);\n                }\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImplTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.powermock.configuration.Configuration;\nimport org.powermock.configuration.ConfigurationFactory;\nimport org.powermock.configuration.GlobalConfiguration;\nimport org.powermock.configuration.PowerMockConfiguration;\nimport org.powermock.core.classloader.annotations.PowerMockIgnore;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\n@SuppressWarnings(\"unchecked\")\npublic class PowerMockIgnorePackagesExtractorImplTest {\n    \n    private PowerMockIgnorePackagesExtractorImpl objectUnderTest;\n    \n    @Before\n    public void setUp() throws Exception {\n        GlobalConfiguration.clear();\n        objectUnderTest = new PowerMockIgnorePackagesExtractorImpl();\n    }\n    \n    @After\n    public void tearDown() throws Exception {\n        GlobalConfiguration.clear();\n    }\n    \n    @Test\n    public void should_find_ignore_packages_in_the_whole_class_hierarchy() throws Exception {\n        final String[] values = {\"ignore0\", \"ignore1\", \"ignore2\", \"ignore3\"};\n        final String[] expectedValues = calculateExpectedValues(values);\n    \n        final String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(IgnoreAnnotatedDemoClass.class);\n    \n        assertThat(packagesToIgnore)\n            .as(\"Packages added to ignore\")\n            .hasSize(expectedValues.length)\n            .containsExactlyInAnyOrder(expectedValues);\n    }\n    \n    @Test\n    public void should_scan_interfaces_when_search_package_to_ignore() {\n        final String[] values = {\"ignore4\", \"ignore5\", \"ignore6\"};\n    \n        String[] expected = calculateExpectedValues(values);\n    \n        final String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(IgnoreAnnotationFromInterfaces.class);\n    \n        assertThat(packagesToIgnore)\n            .as(\"Packages from interfaces added to ignore\")\n            .hasSize(expected.length)\n            .contains(expected);\n        \n    }\n    \n    @Test\n    public void should_include_global_powermock_ignore_to_list_of_package_to_ignore() {\n        final String[] globalIgnore = {\"org.somepacakge.*\", \"org.otherpackage.Class\"};\n        \n        GlobalConfiguration.setConfigurationFactory(new ConfigurationFactory() {\n            @Override\n            public <T extends Configuration<T>> T create(final Class<T> configurationType) {\n                PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration();\n                \n                powerMockConfiguration.setGlobalIgnore(globalIgnore);\n                \n                return (T) powerMockConfiguration;\n            }\n        });\n        \n        String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(ClassWithoutAnnotation.class);\n        \n        assertThat(packagesToIgnore)\n            .as(\"Packages from configuration is added to ignore\")\n            .hasSize(2)\n            .containsOnly(globalIgnore);\n    }\n    \n    @Test\n    public void should_not_include_global_powermock_ignore_when_annotation_use_global_ignore_false() {\n        \n        final String[] globalIgnore = {\"org.somepacakge.*\", \"org.otherpackage.Class\"};\n        \n        GlobalConfiguration.setConfigurationFactory(new ConfigurationFactory() {\n            @Override\n            public <T extends Configuration<T>> T create(final Class<T> configurationType) {\n                PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration();\n                \n                powerMockConfiguration.setGlobalIgnore(globalIgnore);\n                \n                return (T) powerMockConfiguration;\n            }\n        });\n        \n        String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(ClassWithAnnotationUseFalse.class);\n        \n        assertThat(packagesToIgnore)\n            .as(\"Packages from global ignore is not added\")\n            .hasSize(2)\n            .containsOnly(\"ignore6\", \"ignore5\");\n    }\n    \n    @Test\n    public void should_not_include_global_powermock_ignore_when_annotation_use_global_ignore_false_on_parent_class() {\n        \n        final String[] globalIgnore = {\"org.somepacakge.*\", \"org.otherpackage.Class\"};\n        \n        GlobalConfiguration.setConfigurationFactory(new ConfigurationFactory() {\n            @Override\n            public <T extends Configuration<T>> T create(final Class<T> configurationType) {\n                PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration();\n                \n                powerMockConfiguration.setGlobalIgnore(globalIgnore);\n                \n                return (T) powerMockConfiguration;\n            }\n        });\n        \n        String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(IgnoreAnnotatedWithGlobalIgnoreParent.class);\n        \n        assertThat(packagesToIgnore)\n            .as(\"Packages from global ignore is not added\")\n            .hasSize(4)\n            .containsOnly(\"ignore0\", \"ignore1\", \"ignore6\", \"ignore5\");\n    }\n    \n    private String[] calculateExpectedValues(final String[] values) {\n        final PowerMockConfiguration configuration = GlobalConfiguration.powerMockConfiguration();\n        final int length = configuration.getGlobalIgnore().length;\n        \n        final int expectedLength = length + values.length;\n        String[] expected = new String[expectedLength];\n        \n        System.arraycopy(configuration.getGlobalIgnore(), 0, expected, 0, length);\n        System.arraycopy(values, 0, expected, length, values.length);\n        return expected;\n    }\n    \n    private static class ClassWithoutAnnotation {\n    \n    }\n    \n    @PowerMockIgnore({\"ignore0\", \"ignore1\"})\n    private class IgnoreAnnotatedDemoClass extends IgnoreAnnotatedDemoClassParent {\n    \n    }\n    \n    @PowerMockIgnore(\"ignore2\")\n    private class IgnoreAnnotatedDemoClassParent extends IgnoreAnnotatedDemoClassGrandParent {\n    \n    }\n    \n    @PowerMockIgnore(\"ignore3\")\n    private class IgnoreAnnotatedDemoClassGrandParent {\n    \n    }\n    \n    private static class IgnoreAnnotationFromInterfaces implements IgnoreAnnotatedDemoInterfaceParent1, IgnoreAnnotatedDemoInterfaceParent2 {\n    \n    }\n    \n    @PowerMockIgnore(\"ignore5\")\n    private interface IgnoreAnnotatedDemoInterfaceGrandParent {\n    \n    }\n    \n    @PowerMockIgnore(\"ignore4\")\n    private interface IgnoreAnnotatedDemoInterfaceParent1 extends IgnoreAnnotatedDemoInterfaceGrandParent {\n    \n    }\n    \n    @PowerMockIgnore(\"ignore6\")\n    private interface IgnoreAnnotatedDemoInterfaceParent2 extends IgnoreAnnotatedDemoInterfaceGrandParent {\n    }\n    \n    @PowerMockIgnore(value = \"ignore6\", globalIgnore = false)\n    private class ClassWithAnnotationUseFalse implements IgnoreAnnotatedDemoInterfaceGrandParent {\n    \n    }\n    \n    @PowerMockIgnore({\"ignore0\", \"ignore1\"})\n    private class IgnoreAnnotatedWithGlobalIgnoreParent extends ClassWithAnnotationUseFalse {\n        \n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImplTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.tests.utils.impl;\n\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.reflect.Whitebox;\n\nimport java.io.Serializable;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\n/**\n * Unit tests for the {@link PrepareForTestExtractorImpl} class.\n * \n */\npublic class PrepareForTestExtractorImplTest {\n\n    /**\n     * Makes sure that issue <a\n     * href=\"http://code.google.com/p/powermock/issues/detail?id=81\">81</a> is\n     * solved.\n     */\n    @Test\n    public void assertThatInterfacesWorks() throws Exception {\n        final PrepareForTestExtractorImpl tested = new PrepareForTestExtractorImpl();\n        final Set<String> hashSet = new HashSet<String>();\n        Whitebox.invokeMethod(tested, \"addClassHierarchy\", hashSet, Serializable.class);\n        assertEquals(1, hashSet.size());\n        assertEquals(Serializable.class.getName(), hashSet.iterator().next());\n    }\n\n    /**\n     * Makes sure that issue <a\n     * href=\"http://code.google.com/p/powermock/issues/detail?id=111\">111</a> is\n     * solved.\n     */\n    @Test\n    public void shouldFindClassesToPrepareForTestInTheWholeClassHierarchy() throws Exception {\n        final PrepareForTestExtractorImpl tested = new PrepareForTestExtractorImpl();\n        final String[] classesToPrepare = tested.getTestClasses(PrepareForTestDemoClass.class);\n        assertEquals(8, classesToPrepare.length);\n        final String classPrefix = \"Class\";\n        final List<String> classesToPrepareList = Arrays.asList(classesToPrepare);\n        final int noOfClassesExplicitlyPrepared = 5;\n        for (int i = 0; i < noOfClassesExplicitlyPrepared; i++) {\n            final String className = classPrefix + (i + 1);\n            assertTrue(\"Should prepare \" + className, classesToPrepareList.contains(className));\n        }\n        // We assert that the implicit classes (the test cases) are also added.\n        assertTrue(classesToPrepareList.contains(PrepareForTestDemoClass.class.getName()));\n        assertTrue(classesToPrepareList.contains(PrepareForTestDemoClassParent.class.getName()));\n        assertTrue(classesToPrepareList.contains(PrepareForTestDemoClassGrandParent.class.getName()));\n    }\n}\n\n@PrepareForTest(fullyQualifiedNames = { \"Class1\", \"Class2\" })\nclass PrepareForTestDemoClass extends PrepareForTestDemoClassParent {\n\n}\n\n@PrepareForTest(fullyQualifiedNames = { \"Class3\" })\nclass PrepareForTestDemoClassParent extends PrepareForTestDemoClassGrandParent {\n\n}\n\n@PrepareForTest(fullyQualifiedNames = { \"Class4\", \"Class5\" })\nclass PrepareForTestDemoClassGrandParent {\n\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/utils/JavaVersionTest.java",
    "content": "package org.powermock.utils;\n\nimport org.junit.Test;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\n\npublic class JavaVersionTest {\n\n    @Test\n    public void should_return_true_for_current_version_that_if_high_than16() {\n        assertThat(JavaVersion.JAVA_RECENT.atLeast(JavaVersion.JAVA_1_6))\n                .isTrue();\n    }\n\n}"
  },
  {
    "path": "powermock-core/src/test/java/org/powermock/utils/NumberUtilsTest.java",
    "content": "package org.powermock.utils;\n\nimport org.assertj.core.data.Offset;\nimport org.junit.Test;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class NumberUtilsTest {\n\n    @Test\n    public void should_parse_and_return_float() {\n        assertThat(NumberUtils.toFloat(\"133.1\", 0.0f))\n                .as(\"String parsed to float\")\n                .isEqualTo(133.1f, Offset.offset(0.01f));\n\n    }\n\n    @Test\n    public void should_return_default_value_when_cannot_parse() {\n        assertThat(NumberUtils.toFloat(\"11,1\", 0.0f))\n                .as(\"String parsed to float\")\n                .isEqualTo(0.0f, Offset.offset(0.01f));\n    }\n\n    @Test\n    public void should_return_default_value_when_string_is_null() {\n        assertThat(NumberUtils.toFloat(null, 0.0f))\n                .as(\"String parsed to float\")\n                .isEqualTo(0.0f, Offset.offset(0.01f));\n    }\n\n}"
  },
  {
    "path": "powermock-core/src/test/java/powermock/test/support/ClassForMockClassLoaderTestCase.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage powermock.test.support;\n\n\npublic class ClassForMockClassLoaderTestCase {\n    \n    public String description() {\n        return \"This class is used for MockClassLoaderTest and located here only because package 'org.powermock.core' is always ignored.\";\n    }\n    \n}\n"
  },
  {
    "path": "powermock-core/src/test/java/powermock/test/support/ClassWithLargeMethods.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage powermock.test.support;\n\npublic class ClassWithLargeMethods {\n\n    public static class MethodLowerThanLimit {\n        /**\n         * Method size after instrumentation is equal to 42989\n         */\n        public static String init() {\n            String a = \"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            return a;\n        }\n    }\n\n    public static class MethodGreaterThanLimit {\n        /**\n         * Method size after instrumentation is equal to 79522\n         */\n        public static String init() {\n            String a = \"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n            String b = \"B\";\n            b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";\n            b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";\n            b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";\n            b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";\n            b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";\n            b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";\n            b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";b+=\"B\";\n            return a + b;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/java/powermock/test/support/MainMockTransformerTestSupport.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage powermock.test.support;\n\nimport org.powermock.core.classloader.MockClassLoaderConfiguration;\nimport powermock.test.support.MainMockTransformerTestSupport.ConstructorCall.SupperClassThrowsException;\n\n/**\n * This class is used when running tests for different {@link org.powermock.core.transformers.MockTransformer}. It is\n * placed in this package because classes in org.powermock.core.* are deferred by:\n * {@link MockClassLoaderConfiguration#getDeferPackages()}.\n * Additionally, the class must be modified when it is loaded, and as such not in {@link MockClassLoaderConfiguration#shouldLoadWithMockClassloaderWithoutModifications(String)}.\n */\npublic class MainMockTransformerTestSupport {\n    \n    public static class StaticInitialization {\n        public static String value;\n        \n        static {\n            value = \"Init\";\n        }\n    }\n    \n    public interface SomeInterface {\n    \n    }\n    \n    public interface ParameterInterface {\n    \n    }\n    \n    public static class ConstructorCall {\n        \n        public static class SupperClassThrowsException {\n    \n            public static final String MESSAGE = \"Constructor of super class has been called\";\n    \n            public SupperClassThrowsException(String name, double value) {\n                throw new IllegalArgumentException(MESSAGE);\n            }\n    \n            public SupperClassThrowsException(final ParameterImpl value) {\n                throw new IllegalArgumentException(MESSAGE);\n            }\n    \n            public SupperClassThrowsException(final long... array) {\n                throw new IllegalArgumentException(MESSAGE);\n            }\n    \n            public void aVoid() {\n        \n            }\n    \n            public void bVoid(final String lname, final long lvalue) {\n        \n            }\n        }\n    \n    }\n    \n    public static class SuperClassWithObjectMethod {\n    \n        public static boolean syntheticMethodIsCalled = false;\n        \n        public void doSomething(Object o) {\n            \n        }\n    }\n    \n    public static class SubclassWithBridgeMethod extends SuperClassWithObjectMethod {\n        public void doSomething(String s) {\n            \n        }\n    }\n    \n    public static class SupportClasses {\n        \n        private static final Object finalStaticField = new Object();\n        private static transient final Object finalStaticTransientField = new Object();\n        private final Object finalField = new Object();\n        \n        public enum EnumClass {\n            VALUE\n        }\n        \n        public final static class StaticFinalInnerClass {\n        }\n        \n        public final static class FinalInnerClass {\n        }\n        \n        private final static class PrivateStaticFinalInnerClass {\n        }\n        \n        public static class MultipleConstructors {\n            \n            public MultipleConstructors() {}\n            \n            protected MultipleConstructors(String s) {}\n            \n            MultipleConstructors(int i) {}\n            \n            private MultipleConstructors(Boolean[] array) {}\n            \n            protected MultipleConstructors(int[] iarray, boolean b, String[] sarray) {}\n        }\n        \n        public static class PublicSuperClass {\n    \n            public PublicSuperClass(String name) {\n            \n            }\n            \n        }\n        \n        \n        class SuperClass {\n        }\n        \n        public class SubClass extends SuperClass {\n            public void dummyMethod() {}\n        }\n    }\n    \n    public static class SuperClassCallSuperConstructor extends SupperClassThrowsException {\n        private final String field;\n    \n        public SuperClassCallSuperConstructor(final String name, String field, final double value) {\n            super(name, value);\n            this.field = field;\n        \n            String lname = name + \"(a)\";\n            long lvalue = (long) value * 2;\n        \n            if (lname == null) {\n                aVoid();\n            } else {\n                bVoid(lname, lvalue);\n            }\n            cVoid(lname, lvalue);\n        }\n    \n        private void cVoid(final String lname, final long lvalue) {\n        \n        }\n    }\n    \n    public static class SuperClassCallSuperConstructorWithCast extends SupperClassThrowsException {\n        \n        public SuperClassCallSuperConstructorWithCast(final ParameterInterface value) {\n            super((ParameterImpl) value);\n        }\n    }\n    \n    public static class SuperClassCallSuperConstructorWithVararg extends SupperClassThrowsException {\n        \n        public SuperClassCallSuperConstructorWithVararg(final long... array) {\n            super(array);\n        }\n    }\n    \n    public static class ParameterImpl implements ParameterInterface {\n    \n    \n    }\n    \n    public static class StaticVoidMethodsTestClass {\n        \n        private static Object field;\n        \n        private static String lname;\n        private static long value;\n        \n        public static void voidMethod(final String name, String field, final double value)\n        \n        {\n            String lname = name + \"(a)\";\n            long lvalue = (long) value * 2;\n            \n            if (name == null) {\n                aVoid(lvalue);\n            } else {\n                bVoid(lname);\n            }\n            \n            StaticVoidMethodsTestClass.field = field;\n        }\n        \n        private static void bVoid(final String lname) {\n            StaticVoidMethodsTestClass.lname = lname;\n        }\n        \n        private static void aVoid(final long value) {\n            StaticVoidMethodsTestClass.value = value;\n        }\n    }\n    \n    public static class VoidMethodsTestClass {\n        \n        private Object field;\n        \n        private String lname;\n        private long value;\n        \n        public void voidMethod(final String name, String field, final double value) {\n            String lname = name + \"(a)\";\n            long lvalue = (long) value * 2;\n            \n            if (name == null) {\n                aVoid(lvalue);\n            } else {\n                voidPrivateMethod(lname);\n            }\n            \n            this.field = field;\n        }\n        \n        public void finalVoidMethod(final String name, String field, final double value) {\n            String lname = name + \"(a)\";\n            long lvalue = (long) value * 2;\n            \n            if (name == null) {\n                aVoid(lvalue);\n            } else {\n                voidPrivateMethod(lname);\n            }\n            \n            this.field = field;\n        }\n    \n        private void voidPrivateMethod(final String lname) {\n            this.lname = lname;\n        }\n        \n        private void aVoid(final long value) {\n            this.value = value;\n        }\n    }\n    \n    public static class ReturnMethodsTestClass {\n        \n        private String lname;\n        private long value;\n        \n        public String returnMethod(final String name, String field, final double value) {\n            long lvalue = (long) value * 2;\n    \n            if (name == null) {\n                return aVoid(lvalue);\n            } else {\n                return privateReturnMethod(name);\n            }\n        }\n        \n        public final String finalReturnMethod(final String name, String field, final double value) {\n            long lvalue = (long) value * 2;\n            \n            if (name == null) {\n                return aVoid(lvalue);\n            } else {\n                return privateReturnMethod(name);\n            }\n        }\n    \n        private String privateReturnMethod(final String name) {\n            final String lname = name + \"(a)\";\n            this.lname = lname;\n            return lname;\n        }\n    \n        private String aVoid(final long value) {\n            this.value = value;\n            return \"\" + value;\n        }\n    }\n    \n    public static abstract class AbstractMethodTestClass {\n        public abstract String returnMethod(final String name, String field, final double value);\n    }\n    \n    public static class NativeMethodsTestClass {\n        public static native String nativeStaticReturnMethod(final String name);\n        public native String nativeReturnMethod(final String name);\n    }\n    \n    public static class ChildOfNativeMethodsTestClass extends NativeMethodsTestClass {\n        \n    }\n    \n    public static class ParentTestClass {\n        \n        public static class NestedTestClass{\n            \n            \n            public NestedTestClass() {}\n            \n            protected NestedTestClass(String s) {}\n            \n            NestedTestClass(int i) {}\n            \n            private NestedTestClass(Boolean[] array) {}\n            \n            protected NestedTestClass(int[] iarray, boolean b, String[] sarray) {}\n            \n        }\n    }\n    \n    public static class ClassWithoutHashCode {\n        \n    }\n}"
  },
  {
    "path": "powermock-core/src/test/java/powermock/test/support/TestWithTwoTestMethods.java",
    "content": "package powermock.test.support;\n\nimport org.junit.Test;\n\npublic class TestWithTwoTestMethods {\n    \n    @Test\n    public void test_method_1() {\n    }\n    \n    @Test\n    public void test_method_2() {\n    \n    }\n    \n    \n    public static class NestedTestWithTwoTestMethods {\n        \n        @Test\n        public void test_nested_method_1() {\n        }\n        \n        @Test\n        public void test_nested_method_2() {\n        \n        }\n        \n    }\n}\n"
  },
  {
    "path": "powermock-core/src/test/resources/org/powermock/core/classloader/foo/bar/baz/test.txt",
    "content": "This is the droid that you are looking for..."
  },
  {
    "path": "powermock-core/src/test/resources/org/powermock/extensions/test.properties",
    "content": "mockito.mock-maker-class=TestMockMaker\npowermock.global-ignore=org.somepacckage.*,org.other.Class"
  },
  {
    "path": "powermock-core/src/test/resources/org/powermock/extensions/test_configuration.properties",
    "content": "powermock.global-ignore=org.somepackage\npowermock.byte-code-framework=Javassist"
  },
  {
    "path": "powermock-core/src/test/resources/org/powermock/extensions/test_with_alias.properties",
    "content": "mockito.mock-maker-class=alias"
  },
  {
    "path": "powermock-core/src/test/resources/org/powermock/extensions/test_without_prefix.properties",
    "content": "mock-maker-class=TestMockMaker"
  },
  {
    "path": "powermock-core/src/test/resources/org/powermock/test_default_configuration.properties",
    "content": "powermock.global-ignore=org.powermock.core*\npowermock.byte-code-framework=Javassist"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/jmockit-license.txt",
    "content": "The JMockit Testing Toolkit\nCopyright (c) 2006-2011 Rogério Liesenfeld\n\nPermission is hereby granted, free of charge, to any person obtaining \na copy of this software and associated documentation files (the \n\"Software\"), to deal in the Software without restriction, including \nwithout limitation the rights to use, copy, modify, merge, publish, \ndistribute, sublicense, and/or sell copies of the Software, and to \npermit persons to whom the Software is furnished to do so, subject to \nthe following conditions:\n\nThe above copyright notice and this permission notice shall be \nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY \nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE \nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/AgentInitializationException.java",
    "content": "/*\n * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Sun designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Sun in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,\n * CA 95054 USA or visit www.sun.com if you need additional information or\n * have any questions.\n */\npackage com.sun.tools.attach;\n\n/**\n * The exception thrown when an agent fails to initialize in the target Java virtual machine.\n * <p/>\n * <p> This exception is thrown by {@link\n * VirtualMachine#loadAgent VirtualMachine.loadAgent},\n * {@link VirtualMachine#loadAgentLibrary\n * VirtualMachine.loadAgentLibrary}, {@link\n * VirtualMachine#loadAgentPath VirtualMachine.loadAgentPath}\n * methods if an agent, or agent library, cannot be initialized.\n * When thrown by <tt>VirtualMachine.loadAgentLibrary</tt>, or\n * <tt>VirtualMachine.loadAgentPath</tt> then the exception encapsulates\n * the error returned by the agent's {@code Agent_OnAttach} function.\n * This error code can be obtained by invoking the {@link #returnValue() returnValue} method.\n */\npublic final class AgentInitializationException extends Exception\n{\n   private static final long serialVersionUID = -1508756333332806353L;\n\n   private final int returnValue;\n\n   /**\n    * Constructs an {@code AgentInitializationException} with\n    * no detail message.\n    */\n   public AgentInitializationException()\n   {\n      returnValue = 0;\n   }\n\n   /**\n    * Constructs an {@code AgentInitializationException} with the specified detail message.\n    *\n    * @param s the detail message.\n    */\n   public AgentInitializationException(String s)\n   {\n      super(s);\n      returnValue = 0;\n   }\n\n   /**\n    * Constructs an {@code AgentInitializationException} with\n    * the specified detail message and the return value from the\n    * execution of the agent's {@code Agent_OnAttach} function.\n    *\n    * @param s           the detail message.\n    * @param returnValue the return value\n    */\n   public AgentInitializationException(String s, int returnValue)\n   {\n      super(s);\n      this.returnValue = returnValue;\n   }\n\n   /**\n    * If the exception was created with the return value from the agent\n    * {@code Agent_OnAttach} function then this returns that value,\n    * otherwise returns {@code 0}. </p>\n    */\n   public int returnValue()\n   {\n      return returnValue;\n   }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/AgentLoadException.java",
    "content": "/*\n * Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Sun designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Sun in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,\n * CA 95054 USA or visit www.sun.com if you need additional information or\n * have any questions.\n */\npackage com.sun.tools.attach;\n\n/**\n * The exception thrown when an agent cannot be loaded into the target Java virtual machine.\n * <p/>\n * <p> This exception is thrown by {@link\n * VirtualMachine#loadAgent VirtualMachine.loadAgent} or\n * {@link VirtualMachine#loadAgentLibrary\n * VirtualMachine.loadAgentLibrary}, {@link VirtualMachine#loadAgentPath loadAgentPath} methods\n * if the agent, or agent library, cannot be loaded.\n */\npublic final class AgentLoadException extends Exception\n{\n   private static final long serialVersionUID = 688047862952114238L;\n\n   /**\n    * Constructs an {@code AgentLoadException} with\n    * no detail message.\n    */\n   public AgentLoadException()\n   {\n   }\n\n   /**\n    * Constructs an {@code AgentLoadException} with the specified detail message.\n    */\n   public AgentLoadException(String s)\n   {\n      super(s);\n   }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/AttachNotSupportedException.java",
    "content": "/*\n * Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Sun designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Sun in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,\n * CA 95054 USA or visit www.sun.com if you need additional information or\n * have any questions.\n */\npackage com.sun.tools.attach;\n\n/**\n * Thrown by {@link VirtualMachine#attach VirtalMachine.attach} when attempting to attach to a Java\n * virtual machine for which a compatible {@link com.sun.tools.attach.spi.AttachProvider\n * AttachProvider} does not exist. It is also thrown by {@link\n * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine\n * AttachProvider.attachVirtualMachine} if the provider attempts to\n * attach to a Java virtual machine with which it not compatible.\n */\npublic final class AttachNotSupportedException extends Exception\n{\n   private static final long serialVersionUID = 3391824968260177264L;\n\n   /**\n    * Constructs an {@code AttachNotSupportedException} with no detail message.\n    */\n   public AttachNotSupportedException()\n   {\n   }\n\n   /**\n     * Constructs an {@code AttachNotSupportedException} with\n    * the specified detail message.\n    *\n    * @param s the detail message.\n    */\n   public AttachNotSupportedException(String s)\n   {\n      super(s);\n   }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachine.java",
    "content": "/*\n * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Sun designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Sun in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,\n * CA 95054 USA or visit www.sun.com if you need additional information or\n * have any questions.\n */\npackage com.sun.tools.attach;\n\nimport com.sun.tools.attach.spi.AttachProvider;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Properties;\n\n/**\n * <p>\n * A Java virtual machine.\n * </p>\n * <p> A {@code VirtualMachine} represents a Java virtual machine to which this\n * Java virtual machine has attached. The Java virtual machine to which it is\n * attached is sometimes called the <i>target virtual machine</i>, or <i>target VM</i>.\n * An application (typically a tool such as a managemet console or profiler) uses a\n * VirtualMachine to load an agent into the target VM. For example, a profiler tool\n * written in the Java Language might attach to a running application and load its\n * profiler agent to profile the running application. </p>\n * <p> A VirtualMachine is obtained by invoking the {@link #attach(String) attach} method\n * with an identifier that identifies the target virtual machine. The identifier is\n * implementation-dependent but is typically the process identifier (or pid) in\n * environments where each Java virtual machine runs in its own operating system process.\n * Alternatively, a {@code VirtualMachine} instance is obtained by invoking the\n * {@link #attach(VirtualMachineDescriptor) attach} method with a {@link\n * com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor} obtained\n * from the list of virtual machine descriptors returned by the {@link #list list} method.\n * Once a reference to a virtual machine is obtained, the {@link #loadAgent loadAgent},\n * {@link #loadAgentLibrary loadAgentLibrary}, and {@link #loadAgentPath loadAgentPath}\n * methods are used to load agents into target virtual machine. The {@link\n * #loadAgent loadAgent} method is used to load agents that are written in the Java\n * Language and deployed in a {@link java.util.jar.JarFile JAR file}. (See\n * {@link java.lang.instrument} for a detailed description on how these agents\n * are loaded and started). The {@link #loadAgentLibrary loadAgentLibrary} and\n * {@link #loadAgentPath loadAgentPath} methods are used to load agents that\n * are deployed in a dynamic library and make use of the <a\n * href=\"../../../../../../../../technotes/guides/jvmti/index.html\">JVM Tools\n * Interface</a>. </p>\n * <p> In addition to loading agents a VirtualMachine provides read access to the\n * {@link java.lang.System#getProperties() system properties} in the target VM.\n * This can be useful in some environments where properties such as\n * {@code java.home}, {@code os.name}, or {@code os.arch} are\n * used to construct the path to agent that will be loaded into the target VM.\n * <p/>\n * <p> The following example demonstrates how VirtualMachine may be used:</p>\n * <pre>\n *      // attach to target VM\n *      VirtualMachine vm = VirtualMachine.attach(\"2177\");\n *      // get system properties in target VM\n *      Properties props = vm.getSystemProperties();\n *      // construct path to management agent\n *      String home = props.getProperty(\"java.home\");\n *      String agent = home + File.separator + \"lib\" + File.separator\n *          + \"management-agent.jar\";\n *      // load agent into target VM\n *      vm.loadAgent(agent, \"com.sun.management.jmxremote.port=5000\");\n *      // detach\n *      vm.detach();\n * </pre>\n * <p> In this example we attach to a Java virtual machine that is identified by\n * the process identifier {@code 2177}. The system properties from the target\n * VM are then used to construct the path to a <i>management agent</i> which is then\n * loaded into the target VM. Once loaded the client detaches from the target VM. </p>\n * <p> A VirtualMachine is safe for use by multiple concurrent threads. </p>\n *\n * @since 1.6\n */\npublic abstract class VirtualMachine\n{\n   private final AttachProvider provider;\n   private final String id;\n   private volatile int hash;        // 0 => not computed\n\n   /**\n    * Initializes a new instance of this class.\n    *\n    * @param provider The attach provider creating this class.\n    * @param id       The abstract identifier that identifies the Java virtual machine.\n    */\n   protected VirtualMachine(AttachProvider provider, String id)\n   {\n      this.provider = provider;\n      this.id = id;\n   }\n\n   /**\n    * <p>\n    * Return a list of Java virtual machines.\n    * </p>\n    * <p>\n    * This method returns a list of Java {@link com.sun.tools.attach.VirtualMachineDescriptor}\n    * elements.  The list is an aggregation of the virtual machine descriptor lists obtained by\n    * invoking the {@link com.sun.tools.attach.spi.AttachProvider#listVirtualMachines\n    * listVirtualMachines} method of all installed {@link com.sun.tools.attach.spi.AttachProvider\n    * attach providers}.  If there are no Java virtual machines known to any provider then an empty\n    * list is returned.\n    * </p>\n    * @return The list of virtual machine descriptors.\n    */\n   public static List<VirtualMachineDescriptor> list()\n   {\n      List<VirtualMachineDescriptor> l = new ArrayList<VirtualMachineDescriptor>();\n      List<AttachProvider> providers = AttachProvider.providers();\n\n      for (AttachProvider provider : providers) {\n         l.addAll(provider.listVirtualMachines());\n      }\n\n      return l;\n   }\n\n   /**\n    * <p>\n    * Attaches to a Java virtual machine.\n    * </p>\n    * <p>\n    * This method obtains the list of attach providers by invoking the\n    * {@link com.sun.tools.attach.spi.AttachProvider#providers() AttachProvider.providers()} method.\n    * It then iterates overs the list and invokes each provider's {@link\n    * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(java.lang.String)\n    * attachVirtualMachine} method in turn. If a provider successfully\n    * attaches then the iteration terminates, and the VirtualMachine created\n    * by the provider that successfully attached is returned by this method.\n    * If the {@code attachVirtualMachine} method of all providers throws\n    * {@link com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException}\n    * then this method also throws {@code AttachNotSupportedException}.\n    * This means that {@code AttachNotSupportedException} is thrown when\n    * the identifier provided to this method is invalid, or the identifier\n    * corresponds to a Java virtual machine that does not exist, or none\n    * of the providers can attach to it. This exception is also thrown if\n    * {@link com.sun.tools.attach.spi.AttachProvider#providers()\n    * AttachProvider.providers()} returns an empty list.\n    * </p>\n    *\n    * @param id The abstract identifier that identifies the Java virtual machine.\n    * @return A VirtualMachine representing the target VM.\n    * @throws SecurityException           If a security manager has been installed and it denies\n    *                                     {@link com.sun.tools.attach.AttachPermission AttachPermission}\n    *                                     <tt>(\"attachVirtualMachine\")</tt>, or another permission\n    *                                     required by the implementation.\n    * @throws IOException                 If an I/O error occurs\n    */\n   public static VirtualMachine attach(String id) throws AttachNotSupportedException, IOException\n   {\n      List<AttachProvider> providers = AttachProvider.providers();\n      AttachNotSupportedException lastExc = null;\n\n      for (AttachProvider provider : providers) {\n         try {\n            return provider.attachVirtualMachine(id);\n         }\n         catch (AttachNotSupportedException x) {\n            lastExc = x;\n         }\n      }\n\n      throw lastExc;\n   }\n\n   /**\n    * Attaches to a Java virtual machine.\n    * <p/>\n    * This method first invokes the {@link com.sun.tools.attach.VirtualMachineDescriptor#provider()\n    * provider()} method of the given virtual machine descriptor to obtain the attach provider.\n    * It then invokes the attach provider's {@link\n    * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(VirtualMachineDescriptor)\n    * attachVirtualMachine} to attach to the target VM.\n    *\n    * @param   vmd The virtual machine descriptor.\n    *\n    * @return A VirtualMachine representing the target VM.\n    *\n    * @throws SecurityException\n    *          If a security manager has been installed and it denies\n    *          {@link com.sun.tools.attach.AttachPermission AttachPermission}\n    *          <tt>(\"attachVirtualMachine\")</tt>, or another permission\n    *          required by the implementation.\n    *\n    * @throws AttachNotSupportedException\n    *          If the attach provider's {@code attachVirtualmachine}\n    *          throws {@code AttachNotSupportedException}.\n    *\n    * @throws IOException If an I/O error occurs\n    *\n    * @throws NullPointerException If {@code vmd} is {@code null}.\n    */\n   public static VirtualMachine attach(VirtualMachineDescriptor vmd)\n      throws AttachNotSupportedException, IOException\n   {\n      return vmd.provider().attachVirtualMachine(vmd);\n   }\n\n   /**\n    * Detach from the virtual machine.\n    * <p/>\n    * After detaching from the virtual machine, any further attempt to invoke\n    * operations on that virtual machine will cause an {@link java.io.IOException\n    * IOException} to be thrown. If an operation (such as {@link #loadAgent\n    * loadAgent} for example) is in progress when this method is invoked then\n    * the behaviour is implementation dependent. In other words, it is\n    * implementation specific if the operation completes or throws <tt>IOException</tt>.\n    * <p/>\n    * If already detached from the virtual machine then invoking this method has no effect.\n    *\n    * @throws IOException If an I/O error occurs\n    */\n   public abstract void detach() throws IOException;\n\n   /**\n    * Returns the provider that created this virtual machine.\n    */\n   public final AttachProvider provider()\n   {\n      return provider;\n   }\n\n   /**\n    * Returns the identifier for this Java virtual machine.\n    */\n   public final String id()\n   {\n      return id;\n   }\n\n   /**\n    * Loads an agent library.\n    * <p/>\n    * A <a href=\"../../../../../../../../technotes/guides/jvmti/index.html\">JVM\n    * TI</a> client is called an <i>agent</i>. It is developed in a native language.\n    * A JVM TI agent is deployed in a platform specific manner but it is typically the\n    * platform equivalent of a dynamic library. This method causes the given agent\n    * library to be loaded into the target VM (if not already loaded).\n    * It then causes the target VM to invoke the {@code Agent_OnAttach} function\n    * as specified in the\n    * <a href=\"../../../../../../../../technotes/guides/jvmti/index.html\"> JVM Tools\n    * Interface</a> specification. Note that the {@code Agent_OnAttach}\n    * function is invoked even if the agent library was loaded prior to invoking\n    * this method.\n    * <p/>\n    * The agent library provided is the name of the agent library. It is interpreted\n    * in the target virtual machine in an implementation-dependent manner. Typically an\n    * implementation will expand the library name into an operating system specific file\n    * name. For example, on UNIX systems, the name <tt>foo</tt> might be expanded to\n    * <tt>libfoo.so</tt>, and located using the search path specified by the\n    * <tt>LD_LIBRARY_PATH</tt> environment variable.\n    * <p/>\n    * If the {@code Agent_OnAttach} function in the agent library returns\n    * an error then an {@link com.sun.tools.attach.AgentInitializationException} is\n    * thrown. The return value from the {@code Agent_OnAttach} can then be\n    * obtained by invoking the {@link\n    * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}\n    * method on the exception.\n    *\n    * @param agentLibrary The name of the agent library.\n    * @param options      The options to provide to the {@code Agent_OnAttach}\n    *                     function (can be {@code null}).\n    * @throws AgentLoadException           If the agent library does not exist, or cannot be loaded for\n    *                                      another reason.\n    * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error\n    * @throws IOException                  If an I/O error occurs\n    * @throws NullPointerException         If {@code agentLibrary} is {@code null}.\n    * @see com.sun.tools.attach.AgentInitializationException#returnValue()\n    */\n   public abstract void loadAgentLibrary(String agentLibrary, String options)\n      throws AgentLoadException, AgentInitializationException, IOException;\n\n   /**\n    * Loads an agent library.\n    * <p/>\n    * This convenience method works as if by invoking:\n    * <p/>\n    * <blockquote><tt>\n    * {@link #loadAgentLibrary(String, String) loadAgentLibrary}(agentLibrary,&nbsp;null);\n    * </tt></blockquote>\n    *\n    * @param agentLibrary The name of the agent library.\n    * @throws AgentLoadException           If the agent library does not exist, or cannot be loaded for\n    *                                      another reason.\n    * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error\n    * @throws IOException                  If an I/O error occurs\n    * @throws NullPointerException         If {@code agentLibrary} is {@code null}.\n    */\n   public void loadAgentLibrary(String agentLibrary)\n      throws AgentLoadException, AgentInitializationException, IOException\n   {\n      loadAgentLibrary(agentLibrary, null);\n   }\n\n   /**\n    * Load a native agent library by full pathname.\n    * <p/>\n    * A <a href=\"../../../../../../../../technotes/guides/jvmti/index.html\">JVM TI</a> client is\n    * called an <i>agent</i>. It is developed in a native language.\n    * A JVM TI agent is deployed in a platform specific manner but it is typically the\n    * platform equivalent of a dynamic library. This method causes the given agent\n    * library to be loaded into the target VM (if not already loaded).\n    * It then causes the target VM to invoke the {@code Agent_OnAttach} function\n    * as specified in the\n    * <a href=\"../../../../../../../../technotes/guides/jvmti/index.html\"> JVM Tools\n    * Interface</a> specification. Note that the {@code Agent_OnAttach}\n    * function is invoked even if the agent library was loaded prior to invoking\n    * this method.\n    * <p/>\n    * The agent library provided is the absolute path from which to load the\n    * agent library. Unlike {@link #loadAgentLibrary loadAgentLibrary}, the library name\n    * is not expanded in the target virtual machine.\n    * <p/>\n    * If the {@code Agent_OnAttach} function in the agent library returns\n    * an error then an {@link com.sun.tools.attach.AgentInitializationException} is\n    * thrown. The return value from the {@code Agent_OnAttach} can then be\n    * obtained by invoking the {@link\n    * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}\n    * method on the exception.\n    *\n    * @param agentPath The full path of the agent library.\n    * @param options   The options to provide to the {@code Agent_OnAttach}\n    *                  function (can be {@code null}).\n    * @throws AgentLoadException           If the agent library does not exist, or cannot be loaded for\n    *                                      another reason.\n    * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error\n    * @throws IOException                  If an I/O error occurs\n    * @throws NullPointerException         If {@code agentPath} is {@code null}.\n    * @see com.sun.tools.attach.AgentInitializationException#returnValue()\n    */\n   public abstract void loadAgentPath(String agentPath, String options)\n      throws AgentLoadException, AgentInitializationException, IOException;\n\n   /**\n    * Load a native agent library by full pathname.\n    * <p/>\n    * This convenience method works as if by invoking:\n    * <p/>\n    * <blockquote><tt>\n    * {@link #loadAgentPath(String, String) loadAgentPath}(agentLibrary,&nbsp;null);\n    * </tt></blockquote>\n    *\n    * @param agentPath The full path to the agent library.\n    * @throws AgentLoadException           If the agent library does not exist, or cannot be loaded for\n    *                                      another reason.\n    * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error\n    * @throws IOException                  If an I/O error occurs\n    * @throws NullPointerException         If {@code agentPath} is {@code null}.\n    */\n   public void loadAgentPath(String agentPath)\n      throws AgentLoadException, AgentInitializationException, IOException\n   {\n      loadAgentPath(agentPath, null);\n   }\n\n\n   /**\n    * Loads an agent.\n    * <p/>\n    * <p> The agent provided to this method is a path name to a JAR file on the file\n    * system of the target virtual machine. This path is passed to the target virtual\n    * machine where it is interpreted. The target virtual machine attempts to start\n    * the agent as specified by the {@link java.lang.instrument} specification.\n    * That is, the specified JAR file is added to the system class path (of the target\n    * virtual machine), and the {@code agentmain} method of the agent class, specified\n    * by the {@code Agent-Class} attribute in the JAR manifest, is invoked. This\n    * method completes when the {@code agentmain} method completes.\n    *\n    * @param agent   Path to the JAR file containing the agent.\n    * @param options The options to provide to the agent's {@code agentmain}\n    *                method (can be {@code null}).\n    * @throws AgentLoadException           If the agent does not exist, or cannot be started in the manner\n    *                                      specified in the {@link java.lang.instrument} specification.\n    * @throws AgentInitializationException If the {@code agentmain} throws an exception\n    * @throws IOException                  If an I/O error occurs\n    * @throws NullPointerException         If {@code agent} is {@code null}.\n    */\n   public abstract void loadAgent(String agent, String options)\n      throws AgentLoadException, AgentInitializationException, IOException;\n\n   /**\n    * Loads an agent.\n    * <p/>\n    * This convenience method works as if by invoking:\n    * <p/>\n    * <blockquote><tt>\n    * {@link #loadAgent(String, String) loadAgent}(agent,&nbsp;null);\n    * </tt></blockquote>\n    *\n    * @param agent Path to the JAR file containing the agent.\n    * @throws AgentLoadException           If the agent does not exist, or cannot be started in the manner\n    *                                      specified in the {@link java.lang.instrument} specification.\n    * @throws AgentInitializationException If the {@code agentmain} throws an exception\n    * @throws IOException                  If an I/O error occurs\n    * @throws NullPointerException         If {@code agent} is {@code null}.\n    */\n   public void loadAgent(String agent)\n      throws AgentLoadException, AgentInitializationException, IOException\n   {\n      loadAgent(agent, null);\n   }\n\n   /**\n    * Returns the current system properties in the target virtual machine.\n    * <p/>\n    * This method returns the system properties in the target virtual\n    * machine. Properties whose key or value is not a <tt>String</tt> are\n    * omitted. The method is approximately equivalent to the invocation of the\n    * method {@link java.lang.System#getProperties System.getProperties}\n    * in the target virtual machine except that properties with a key or\n    * value that is not a <tt>String</tt> are not included.\n    * <p/>\n    * This method is typically used to decide which agent to load into\n    * the target virtual machine with {@link #loadAgent loadAgent}, or\n    * {@link #loadAgentLibrary loadAgentLibrary}. For example, the\n    * {@code java.home} or {@code user.dir} properties might be\n    * use to create the path to the agent library or JAR file.\n    *\n    * @return The system properties\n    * @throws IOException If an I/O error occurs\n    * @see java.lang.System#getProperties\n    * @see #loadAgentLibrary\n    * @see #loadAgent\n    */\n   public abstract Properties getSystemProperties() throws IOException;\n\n   /**\n    * Returns the current <i>agent properties</i> in the target virtual\n    * machine.\n    * <p/>\n    * The target virtual machine can maintain a list of properties on\n    * behalf of agents. The manner in which this is done, the names of the\n    * properties, and the types of values that are allowed, is implementation\n    * specific. Agent properties are typically used to store communication\n    * end-points and other agent configuration details. For example, a debugger\n    * agent might create an agent property for its transport address.\n    * <p/>\n    * This method returns the agent properties whose key and value is a\n    * <tt>String</tt>. Properties whose key or value is not a <tt>String</tt>\n    * are omitted. If there are no agent properties maintained in the target\n    * virtual machine then an empty property list is returned.\n    *\n    * @return The agent properties\n    * @throws IOException If an I/O error occurs\n    */\n   public abstract Properties getAgentProperties() throws IOException;\n\n   /**\n    * Returns a hash-code value for this VirtualMachine. The hash\n    * code is based upon the VirtualMachine's components, and satisfies\n    * the general contract of the Object.hashCode method.\n    *\n    * @return A hash-code value for this virtual machine\n    */\n   @Override\n   public int hashCode()\n   {\n      if (hash != 0) {\n         return hash;\n      }\n\n      hash = provider.hashCode() * 127 + id.hashCode();\n      return hash;\n   }\n\n   /**\n    * Tests this VirtualMachine for equality with another object.\n    * <p/>\n    * <p> If the given object is not a VirtualMachine then this\n    * method returns <tt>false</tt>. For two VirtualMachines to\n    * be considered equal requires that they both reference the same\n    * provider, and their {@link VirtualMachineDescriptor#id() identifiers} are equal. </p>\n    * <p/>\n    * <p> This method satisfies the general contract of the  method. </p>\n    *\n    * @param ob The object to which this object is to be compared\n    * @return <tt>true</tt> if, and only if, the given object is\n    *         a VirtualMachine that is equal to this\n    *         VirtualMachine.\n    */\n   @Override\n   public boolean equals(Object ob)\n   {\n      if (ob == this) {\n         return true;\n      }\n\n      if (!(ob instanceof VirtualMachine)) {\n         return false;\n      }\n\n      VirtualMachine other = (VirtualMachine) ob;\n\n      return other.provider() == provider() && other.id().equals(id());\n   }\n\n   /**\n    * Returns the string representation of the {@code VirtualMachine}.\n    */\n   @Override\n   public String toString()\n   {\n      return provider.toString() + \": \" + id;\n   }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java",
    "content": "/*\n * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Sun designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Sun in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,\n * CA 95054 USA or visit www.sun.com if you need additional information or\n * have any questions.\n */\npackage com.sun.tools.attach;\n\nimport com.sun.tools.attach.spi.AttachProvider;\n\n/**\n * Describes a Java virtual machine.\n * <p/>\n * <p> A {@code VirtualMachineDescriptor} is a container class used to\n * describe a Java virtual machine. It encapsulates an identifier that identifies\n * a target virtual machine, and a reference to the {@link\n * com.sun.tools.attach.spi.AttachProvider AttachProvider} that should be used\n * when attempting to attach to the virtual machine. The identifier is\n * implementation-dependent but is typically the process identifier (or pid)\n * environments where each Java virtual machine runs in its own operating system\n * process. </p>\n * <p/>\n * <p> A {@code VirtualMachineDescriptor} also has a {@link #displayName() displayName}.\n * The display name is typically a human readable string that a tool might\n * display to a user. For example, a tool that shows a list of Java\n * virtual machines running on a system might use the display name rather\n * than the identifier. A {@code VirtualMachineDescriptor} may be\n * created without a <i>display name</i>. In that case the identifier is\n * used as the <i>display name</i>.\n * <p/>\n * <p> {@code VirtualMachineDescriptor} instances are typically created by\n * invoking the {@link VirtualMachine#list VirtualMachine.list()}\n * method. This returns the complete list of descriptors to describe the\n * Java virtual machines known to all installed {@link\n * com.sun.tools.attach.spi.AttachProvider attach providers}.\n *\n * @since 1.6\n */\npublic final class VirtualMachineDescriptor\n{\n   private AttachProvider provider;\n   private String id;\n   private String displayName;\n\n   private volatile int hash;        // 0 => not computed\n\n   /**\n    * Creates a virtual machine descriptor from the given components.\n    *\n    * @param provider    The AttachProvider to attach to the Java virtual machine.\n    * @param id          The virtual machine identifier.\n    * @param displayName The display name.\n    * @throws NullPointerException If any of the arguments are {@code null}\n    */\n   public VirtualMachineDescriptor(AttachProvider provider, String id, String displayName)\n   {\n      if (provider == null) {\n         throw new NullPointerException(\"provider cannot be null\");\n      }\n\n      if (id == null) {\n         throw new NullPointerException(\"identifier cannot be null\");\n      }\n\n      if (displayName == null) {\n         throw new NullPointerException(\"display name cannot be null\");\n      }\n\n      this.provider = provider;\n      this.id = id;\n      this.displayName = displayName;\n   }\n\n   /**\n    * Creates a virtual machine descriptor from the given components.\n    * <p/>\n    * <p> This convenience constructor works as if by invoking the\n    * three-argument constructor as follows:\n    * <p/>\n    * <blockquote><tt>\n    * new&nbsp;{@link #VirtualMachineDescriptor(com.sun.tools.attach.spi.AttachProvider, String, String)\n    * VirtualMachineDescriptor}(provider, &nbsp;id, &nbsp;id);\n    * </tt></blockquote>\n    * <p/>\n    * <p> That is, it creates a virtual machine descriptor such that\n    * the <i>display name</i> is the same as the virtual machine\n    * identifier.\n    *\n    * @param provider The AttachProvider to attach to the Java virtual machine.\n    * @param id       The virtual machine identifier.\n    * @throws NullPointerException If <tt>provider</tt> or <tt>id</tt> is <tt>null</tt>.\n    */\n   public VirtualMachineDescriptor(AttachProvider provider, String id)\n   {\n      this(provider, id, id);\n   }\n\n   /**\n    * Return the {@code AttachProvider} that this descriptor references.\n    *\n    * @return The {@code AttachProvider} that this descriptor references.\n    */\n   public AttachProvider provider()\n   {\n      return provider;\n   }\n\n   /**\n    * Return the identifier component of this descriptor.\n    *\n    * @return The identifier component of this descriptor.\n    */\n   public String id()\n   {\n      return id;\n   }\n\n   /**\n    * Return the <i>display name</i> component of this descriptor.\n    *\n    * @return The display name component of this descriptor.\n    */\n   public String displayName()\n   {\n      return displayName;\n   }\n\n   /**\n    * Returns a hash-code value for this VirtualMachineDescriptor. The hash\n    * code is based upon the descriptor's components, and satisfies\n    * the general contract of the Object.hashCode method.\n    *\n    * @return A hash-code value for this descriptor.\n    */\n   @Override\n   public int hashCode()\n   {\n      if (hash != 0) {\n         return hash;\n      }\n\n      hash = provider.hashCode() * 127 + id.hashCode();\n      return hash;\n   }\n\n   /**\n    * Tests this VirtualMachineDescriptor for equality with another object.\n    * <p/>\n    * <p> If the given object is not a VirtualMachineDescriptor then this\n    * method returns <tt>false</tt>. For two VirtualMachineDescriptors to\n    * be considered equal requires that they both reference the same\n    * provider, and their {@link #id() identifiers} are equal. </p>\n    * <p/>\n    * <p> This method satisfies the general contract of the  method. </p>\n    *\n    * @param ob The object to which this object is to be compared\n    * @return <tt>true</tt> if, and only if, the given object is\n    *         a VirtualMachineDescriptor that is equal to this\n    *         VirtualMachineDescriptor.\n    */\n   @Override\n   public boolean equals(Object ob)\n   {\n      if (ob == this)\n         return true;\n      if (!(ob instanceof VirtualMachineDescriptor))\n         return false;\n      VirtualMachineDescriptor other = (VirtualMachineDescriptor) ob;\n      if (other.provider() != this.provider()) {\n         return false;\n      }\n      if (!other.id().equals(this.id())) {\n         return false;\n      }\n      return true;\n   }\n\n   /**\n    * Returns the string representation of the {@code VirtualMachineDescriptor}.\n    */\n   @Override\n   public String toString()\n   {\n      String s = provider.toString() + \": \" + id;\n\n      if (displayName != id) {\n         s += \" \" + displayName;\n      }\n\n      return s;\n   }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/spi/AttachProvider.java",
    "content": "/*\n * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Sun designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Sun in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,\n * CA 95054 USA or visit www.sun.com if you need additional information or\n * have any questions.\n */\npackage com.sun.tools.attach.spi;\n\nimport com.sun.tools.attach.AttachNotSupportedException;\nimport com.sun.tools.attach.VirtualMachine;\nimport com.sun.tools.attach.VirtualMachineDescriptor;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.ServiceLoader;\n\n/**\n * <p>\n * Attach provider class for attaching to a Java virtual machine.\n * <p/>\n * <p> An attach provider is a concrete subclass of this class that has a\n * zero-argument constructor and implements the abstract methods specified\n * below.\n * </p>\n * <p>\n * An attach provider implementation is typically tied to a Java virtual\n * machine implementation, version, or even mode of operation. That is, a specific\n * provider implementation will typically only be capable of attaching to\n * a specific Java virtual machine implementation or version. For example, Sun's\n * JDK implementation ships with provider implementations that can only attach to\n * Sun's <i>HotSpot</i> virtual machine. In general, if an environment\n * consists of Java virtual machines of different versions and from different\n * vendors then there will be an attach provider implementation for each\n * <i>family</i> of implementations or versions.\n * </p>\n * <p> An attach provider is identified by its {@link #name <i>name</i>} and\n * {@link #type <i>type</i>}. The <i>name</i> is typically, but not required to\n * be, a name that corresponds to the VM vendor. The Sun JDK implementation,\n * for example, ships with attach providers that use the name <i>\"sun\"</i>. The\n * <i>type</i> typically corresponds to the attach mechanism. For example, an\n * implementation that uses the Doors inter-process communication mechanism\n * might use the type <i>\"doors\"</i>. The purpose of the name and type is to\n * identify providers in environments where there are multiple providers\n * installed. </p>\n * <p> AttachProvider implementations are loaded and instantiated at the first\n * invocation of the {@link #providers() providers} method. This method\n * attempts to load all provider implementations that are installed on the\n * platform. </p>\n * <p> All of the methods in this class are safe for use by multiple\n * concurrent threads. </p>\n *\n * @since 1.6\n */\npublic abstract class AttachProvider {\n    private static final Object lock = new Object();\n    private static List<AttachProvider> providers;\n    \n    /**\n     * Initializes a new instance of this class.\n     */\n    protected AttachProvider() {}\n    \n    /**\n     * Return this provider's name.\n     *\n     * @return The name of this provider\n     */\n    public abstract String name();\n    \n    /**\n     * Return this provider's type.\n     *\n     * @return The type of this provider\n     */\n    public abstract String type();\n    \n    /**\n     * <p>\n     * Attaches to a Java virtual machine.\n     * <p/>\n     * <p> A Java virtual machine is identified by an abstract identifier. The\n     * nature of this identifier is platform dependent but in many cases it will be the\n     * string representation of the process identifier (or pid). </p>\n     * <p/>\n     * <p>This method parses the identifier and maps the identifier to a Java\n     * virtual machine (in an implementation dependent manner). If the identifier\n     * cannot be parsed by the provider then an {@link\n     * com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException}\n     * is thrown. Once parsed this method attempts to attach to the Java virtual machine.\n     * If the provider detects that the identifier corresponds to a Java virtual machine\n     * that does not exist, or it corresponds to a Java virtual machine that does not support\n     * the attach mechanism implemented by this provider, or it detects that the\n     * Java virtual machine is a version to which this provider cannot attach, then\n     * an <code>AttachNotSupportedException</code> is thrown. </p>\n     *\n     * @param id The abstract identifier that identifies the Java virtual machine.\n     * @return VirtualMachine representing the target virtual machine.\n     * @throws SecurityException           If a security manager has been installed and it denies\n     *                                     {@link com.sun.tools.attach.AttachPermission AttachPermission}\n     *                                     <tt>(\"attachVirtualMachine\")</tt>, or other permission\n     *                                     required by the implementation.\n     * @throws AttachNotSupportedException If the identifier cannot be parsed, or it corresponds to\n     *                                     to a Java virtual machine that does not exist, or it\n     *                                     corresponds to a Java virtual machine which this\n     *                                     provider cannot attach.\n     * @throws IOException                 If some other I/O error occurs\n     * @throws NullPointerException        If <code>id</code> is <code>null</code>\n     */\n    public abstract VirtualMachine attachVirtualMachine(String id)\n        throws AttachNotSupportedException, IOException;\n    \n    /**\n     * <p>\n     * Attaches to a Java virtual machine.\n     * <p/>\n     * <p>\n     * A Java virtual machine can be described using a {@link\n     * com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor}.\n     * This method invokes the descriptor's {@link\n     * com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method\n     * to check that it is equal to this provider. It then attempts to attach to the\n     * Java virtual machine.\n     * </p>\n     *\n     * @param vmd The virtual machine descriptor\n     * @return VirtualMachine representing the target virtual machine.\n     * @throws SecurityException           If a security manager has been installed and it denies\n     *                                     {@link com.sun.tools.attach.AttachPermission AttachPermission}\n     *                                     <tt>(\"attachVirtualMachine\")</tt>, or other permission\n     *                                     required by the implementation.\n     * @throws AttachNotSupportedException If the descriptor's {@link\n     *                                     com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method\n     *                                     returns a provider that is not this provider, or it does not correspond\n     *                                     to a Java virtual machine to which this provider can attach.\n     * @throws IOException                 If some other I/O error occurs\n     * @throws NullPointerException        If <code>vmd</code> is <code>null</code>\n     */\n    public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)\n        throws AttachNotSupportedException, IOException {\n        if (vmd.provider() != this) {\n            throw new AttachNotSupportedException(\"provider mismatch\");\n        }\n        \n        return attachVirtualMachine(vmd.id());\n    }\n    \n    /**\n     * <p>\n     * Lists the Java virtual machines known to this provider.\n     * <p/>\n     * <p>\n     * This method returns a list of {@link com.sun.tools.attach.VirtualMachineDescriptor} elements.\n     * Each <code>VirtualMachineDescriptor</code> describes a Java virtual machine\n     * to which this provider can <i>potentially</i> attach.  There isn't any\n     * guarantee that invoking {@link #attachVirtualMachine(VirtualMachineDescriptor)\n     * attachVirtualMachine} on each descriptor in the list will succeed.\n     * </p>\n     * @return The list of virtual machine descriptors which describe the\n     * Java virtual machines known to this provider (may be empty).\n     */\n    public abstract List<VirtualMachineDescriptor> listVirtualMachines();\n    \n    /**\n     * <p>\n     * Returns a list of the installed attach providers.\n     * <p/>\n     * <p>An AttachProvider is installed on the platform if:\n     * <p/>\n     * <ul>\n     * <li><p>It is installed in a JAR file that is visible to the defining\n     * class loader of the AttachProvider type (usually, but not required\n     * to be, the {@link java.lang.ClassLoader#getSystemClassLoader system\n     * class loader}).</p></li>\n     * <li><p>The JAR file contains a provider configuration named\n     * <tt>com.sun.tools.attach.spi.AttachProvider</tt> in the resource directory\n     * <tt>META-INF/services</tt>. </p></li>\n     * <li><p>The provider configuration file lists the full-qualified class\n     * name of the AttachProvider implementation. </p></li>\n     * </ul>\n     * <p> The format of the provider configuration file is one fully-qualified\n     * class name per line. Space and tab characters surrounding each class name,\n     * as well as blank lines are ignored. The comment character is\n     * <tt>'#'</tt> (<tt>0x23</tt>), and on each line all characters following\n     * the first comment character are ignored. The file must be encoded in\n     * UTF-8. </p>\n     * <p> AttachProvider implementations are loaded and instantiated\n     * (using the zero-arg constructor) at the first invocation of this method.\n     * The list returned by the first invocation of this method is the list\n     * of providers. Subsequent invocations of this method return a list of the same\n     * providers. The list is unmodifable.</p>\n     *\n     * @return A list of the installed attach providers.\n     */\n    @SuppressWarnings({\"Since15\"})\n    public static List<AttachProvider> providers() {\n        synchronized (lock) {\n            if (providers == null) {\n                providers = new ArrayList<AttachProvider>();\n                \n                ServiceLoader<AttachProvider> providerLoader =\n                    ServiceLoader.load(AttachProvider.class, AttachProvider.class.getClassLoader());\n                \n                for (AttachProvider aProviderLoader : providerLoader) {\n                    try {\n                        providers.add(aProviderLoader);\n                    } catch (ThreadDeath td) {\n                        throw td;\n                    } catch (Throwable t) {\n                        // Ignore errors and exceptions.\n                        System.err.println(t);\n                    }\n                }\n            }\n            \n            return Collections.unmodifiableList(providers);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AbstractClassTransformer.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.modules.agent;\n\nimport org.powermock.core.WildcardMatcher;\n\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic abstract class AbstractClassTransformer {\n    \n    private static final List<String> ALWAYS_IGNORED = new LinkedList<String>();\n    private final List<String> USER_IGNORED = Collections.synchronizedList(new LinkedList<String>());\n\n    static {\n        ALWAYS_IGNORED.add(\"org.powermock.*\");\n        ALWAYS_IGNORED.add(\"org.junit.*\");\n        ALWAYS_IGNORED.add(\"org.testng.*\");\n        ALWAYS_IGNORED.add(\"org.assertj.*\");\n        ALWAYS_IGNORED.add(\"org.mockito.*\");\n        ALWAYS_IGNORED.add(\"javassist.*\");\n        ALWAYS_IGNORED.add(\"org.objenesis.*\");\n        ALWAYS_IGNORED.add(\"junit.*\");\n        ALWAYS_IGNORED.add(\"org.hamcrest.*\");\n        ALWAYS_IGNORED.add(\"sun.*\");\n        ALWAYS_IGNORED.add(\"$Proxy*\");\n        ALWAYS_IGNORED.add(\"*CGLIB$$*\");\n        ALWAYS_IGNORED.add(\"*$$PowerMock*\");\n    }     \n\n    public synchronized void setPackagesToIgnore(List<String> packagesToIgnore) {\n        USER_IGNORED.clear();\n        USER_IGNORED.addAll(packagesToIgnore);\n    }\n\n    public void resetPackagesToIgnore() {\n        USER_IGNORED.clear();\n    }\n\n    protected boolean shouldIgnore(String className) {\n        return WildcardMatcher.matchesAny(merge(USER_IGNORED), replaceSlashWithDots(className));\n    }\n\n    private List<String> merge(List<String> userIgnored) {\n        List<String> list = new LinkedList<String>(AbstractClassTransformer.ALWAYS_IGNORED);\n        list.addAll(userIgnored);\n        return Collections.unmodifiableList(list);\n    }\n\n    String replaceSlashWithDots(String className) {\n        return className.replaceAll(\"/\", \".\");\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentInitialization.java",
    "content": "/*\n * The JMockit Testing Toolkit\n * Copyright (c) 2006-2011 Rogério Liesenfeld\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\npackage org.powermock.modules.agent;\n\nimport java.io.File;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.security.CodeSource;\nimport java.util.regex.Pattern;\n\nfinal class AgentInitialization\n{\n    private static final Pattern JAR_REGEX = Pattern.compile(\".*powermock-module-javaagent[-]?[.\\\\d+]*[-]?[A-Z]*.jar\");\n\n    void initializeAccordingToJDKVersion()  {\n        String jarFilePath = discoverPathToJarFile();\n\n        if (PowerMockAgent.jdk6OrLater) {\n            new AgentLoader(jarFilePath).loadAgent();\n        }\n        else if (\"1.5\".equals(PowerMockAgent.javaSpecVersion)) {\n            throw new IllegalStateException(\n                    \"PowerMock has not been initialized. Check that your Java 5 VM has been started with the -javaagent:\" +\n                            jarFilePath + \" command line option.\");\n        }\n        else {\n            throw new IllegalStateException(\"PowerMock requires a Java 5 VM or later.\");\n        }\n    }\n\n    private String discoverPathToJarFile()\n    {\n        String jarFilePath = findPathToJarFileFromClasspath();\n\n        if (jarFilePath == null) {\n            // This can fail for a remote URL, so it is used as a fallback only:\n            jarFilePath = getPathToJarFileContainingThisClass();\n        }\n\n        if (jarFilePath != null) {\n            return jarFilePath;\n        }\n\n        throw new IllegalStateException(\n                \"No jar file with name ending in \\\"powermock-module-javaagent.jar\\\" or \\\"powermock-module-javaagent-nnn.jar\\\" (where \\\"nnn\\\" is a version number) \" +\n                        \"found in the classpath\");\n    }\n\n    private String findPathToJarFileFromClasspath()\n    {\n        String[] classPath = System.getProperty(\"java.class.path\").split(File.pathSeparator);\n\n        for (String cpEntry : classPath) {\n            if (JAR_REGEX.matcher(cpEntry).matches()) {\n                return cpEntry;\n            }\n        }\n\n        return null;\n    }\n\n    private String getPathToJarFileContainingThisClass() {\n        CodeSource codeSource = AgentInitialization.class.getProtectionDomain().getCodeSource();\n\n        if (codeSource == null) {\n            return null;\n        }\n\n        URI jarFileURI; // URI is needed to deal with spaces and non-ASCII characters\n\n        try {\n            jarFileURI = codeSource.getLocation().toURI();\n        }\n        catch (URISyntaxException e) {\n            throw new RuntimeException(e);\n        }\n\n        return new File(jarFileURI).getPath();\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentLoader.java",
    "content": "/*\n * The JMockit Testing Toolkit\n * Copyright (c) 2006-2011 Rogério Liesenfeld\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\npackage org.powermock.modules.agent;\n\nimport com.sun.tools.attach.AgentInitializationException;\nimport com.sun.tools.attach.AgentLoadException;\nimport com.sun.tools.attach.AttachNotSupportedException;\nimport com.sun.tools.attach.VirtualMachine;\nimport com.sun.tools.attach.VirtualMachineDescriptor;\nimport com.sun.tools.attach.spi.AttachProvider;\nimport org.powermock.reflect.Whitebox;\nimport sun.tools.attach.BsdVirtualMachine;\nimport sun.tools.attach.LinuxVirtualMachine;\nimport sun.tools.attach.SolarisVirtualMachine;\nimport sun.tools.attach.WindowsVirtualMachine;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.management.ManagementFactory;\nimport java.util.List;\n\nfinal class AgentLoader {\n    private static final AttachProvider ATTACH_PROVIDER = new AttachProvider() {\n        @Override\n        public String name() {\n            return null;\n        }\n\n        @Override\n        public String type() {\n            return null;\n        }\n\n        @Override\n        public VirtualMachine attachVirtualMachine(String id) {\n            return null;\n        }\n\n        @Override\n        public List<VirtualMachineDescriptor> listVirtualMachines() {\n            return null;\n        }\n    };\n\n    private final String jarFilePath;\n    private final String pid;\n\n    AgentLoader(String jarFilePath) {\n        this.jarFilePath = jarFilePath;\n        pid = discoverProcessIdForRunningVM();\n    }\n\n    private static String discoverProcessIdForRunningVM() {\n        String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();\n        int p = nameOfRunningVM.indexOf('@');\n\n        return nameOfRunningVM.substring(0, p);\n    }\n\n    boolean loadAgent() {\n        VirtualMachine vm;\n\n        if (AttachProvider.providers().isEmpty()) {\n            vm = getVirtualMachineImplementationFromEmbeddedOnes();\n        } else {\n            vm = attachToThisVM();\n        }\n\n        if (vm != null) {\n            loadAgentAndDetachFromThisVM(vm);\n            return true;\n        }\n\n        return false;\n    }\n\n    @SuppressWarnings(\"UseOfSunClasses\")\n    private VirtualMachine getVirtualMachineImplementationFromEmbeddedOnes() {\n        try {\n            Class<? extends VirtualMachine> vmClass;\n\n            if (File.separatorChar == '\\\\') {\n                vmClass = WindowsVirtualMachine.class;\n            } else {\n                String osName = System.getProperty(\"os.name\");\n\n                if (osName.startsWith(\"Linux\") || osName.startsWith(\"LINUX\")) {\n                    vmClass = LinuxVirtualMachine.class;\n                } else if (osName.startsWith(\"Mac OS X\")) {\n                    vmClass = BsdVirtualMachine.class;\n                } else if (osName.startsWith(\"Solaris\")) {\n                    vmClass = SolarisVirtualMachine.class;\n                } else {\n                    return null;\n                }\n            }\n\n            // This is only done with Reflection to avoid the JVM pre-loading all the XyzVirtualMachine classes.\n            Class<?>[] parameterTypes = {AttachProvider.class, String.class};\n\n            VirtualMachine newVM = null;\n            try {\n                newVM = Whitebox.invokeConstructor(vmClass, parameterTypes, new Object[]{ATTACH_PROVIDER, pid});\n            } catch (Exception e) {\n                throw new RuntimeException(e);\n            }\n            return newVM;\n        } catch (UnsatisfiedLinkError e) {\n            throw new IllegalStateException(\"Native library for Attach API not available in this JRE\", e);\n        }\n    }\n\n    private VirtualMachine attachToThisVM() {\n        try {\n            return VirtualMachine.attach(pid);\n        } catch (AttachNotSupportedException e) {\n            throw new RuntimeException(e);\n        } catch (IOException e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n    private void loadAgentAndDetachFromThisVM(VirtualMachine vm) {\n        try {\n            vm.loadAgent(jarFilePath, null);\n            vm.detach();\n        } catch (AgentLoadException e) {\n            throw new RuntimeException(e);\n        } catch (AgentInitializationException e) {\n            throw new RuntimeException(e);\n        } catch (IOException e) {\n            throw new RuntimeException(e);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassTransformer.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.modules.agent;\n\nimport net.bytebuddy.jar.asm.ClassReader;\nimport net.bytebuddy.jar.asm.ClassWriter;\n\nimport java.lang.instrument.ClassFileTransformer;\nimport java.security.ProtectionDomain;\n\npublic class DefinalizingClassTransformer extends AbstractClassTransformer implements ClassFileTransformer {\n    private static final int NO_FLAGS_OR_OPTIONS = 0;\n\n    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {\n        if (loader == null || shouldIgnore(className)) {\n            return null;\n        }\n        final ClassReader reader = new ClassReader(classfileBuffer);\n        final ClassWriter writer = new ClassWriter(NO_FLAGS_OR_OPTIONS);\n        reader.accept(new DefinalizingClassVisitor(writer), NO_FLAGS_OR_OPTIONS);\n        return writer.toByteArray();\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassVisitor.java",
    "content": "package org.powermock.modules.agent;\n\nimport net.bytebuddy.jar.asm.ClassVisitor;\nimport net.bytebuddy.jar.asm.MethodVisitor;\nimport net.bytebuddy.jar.asm.Opcodes;\n\nclass DefinalizingClassVisitor extends ClassVisitor {\n\n    public DefinalizingClassVisitor(ClassVisitor classVisitor) {\n        super(Opcodes.ASM5, classVisitor);\n    }\n\n    @Override\n    public void visit(final int version, final int access, final String name, final String signature, final String superName,\n            final String[] interfaces) {\n        final int accessModifiersWithFinalRemoved = removeFinal(access);\n        super.visit(version, accessModifiersWithFinalRemoved, name, signature, superName, interfaces);\n    }\n\n    @Override\n    public MethodVisitor visitMethod(int access, final String name, final String desc, final String signature,\n                                     final String[] exceptions) {\n        return super.visitMethod(removeFinal(access), name, desc, signature, exceptions);\n    }\n\n    @Override\n    public void visitInnerClass(String name, String outerName, String innerName, int access) {\n        super.visitInnerClass(name, outerName, innerName, removeFinal(access));\n    }\n\n    private int removeFinal(int access) {\n        return access & ~Opcodes.ACC_FINAL;\n    }\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockAgent.java",
    "content": "/*\n * The JMockit Testing Toolkit\n * Copyright (c) 2006-2011 Rogério Liesenfeld\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\npackage org.powermock.modules.agent;\n\nimport org.powermock.utils.JavaVersion;\n\nimport java.io.IOException;\nimport java.lang.instrument.Instrumentation;\n\n/**\n * This is the \"agent class\" that initializes the PowerMock \"Java agent\". It is not intended for use in client code.\n * It must be public, however, so the JVM can call the {@code premain} method, which as the name implies is called\n * <em>before</em> the {@code main} method.\n *\n * @see #premain(String, Instrumentation)\n */\npublic final class PowerMockAgent\n{\n\n\tstatic final String javaSpecVersion = System.getProperty(\"java.specification.version\");\n    static final boolean jdk6OrLater = JavaVersion.JAVA_RECENT.atLeast(JavaVersion.JAVA_1_6);\n\n    private static final PowerMockClassTransformer classTransformer = new PowerMockClassTransformer();\n    \n    private static Instrumentation instrumentation;\n\n    private PowerMockAgent() {}\n\n    /**\n     * This method must only be called by the JVM, to provide the instrumentation object.\n     * In order for this to occur, the JVM must be started with \"-javaagent:powermock-module-javaagent-nnn.jar\" as a command line parameter\n     * (assuming the jar file is in the current directory).\n     *\n     */\n    public static void premain(String agentArgs, Instrumentation inst) throws Exception {\n        initialize(agentArgs, inst);\n    }\n\n    @SuppressWarnings({\"UnusedDeclaration\"})\n    public static void agentmain(String agentArgs, Instrumentation inst) throws Exception {\n        initialize(agentArgs, inst);\n    }\n\n    private static void initialize(String agentArgs, Instrumentation inst) throws IOException {\n        instrumentation = inst;\n        inst.addTransformer(new DefinalizingClassTransformer(), false);\n        inst.addTransformer(classTransformer, true);\n    }\n    \n    public static PowerMockClassTransformer getClasstransformer() {\n\t\treturn classTransformer;\n\t}\n\n    public static Instrumentation instrumentation()  {\n        verifyInitialization();\n        return instrumentation;\n    }\n\n    public static void verifyInitialization()\n    {\n        if (instrumentation == null) {\n            new AgentInitialization().initializeAccordingToJDKVersion();\n        }\n    }\n\n    public static boolean initializeIfNeeded()\n    {\n        if (instrumentation == null) {\n            try {\n                new AgentInitialization().initializeAccordingToJDKVersion();\n                return true;\n            }\n            catch (RuntimeException e) {\n                e.printStackTrace(); // makes sure the exception gets printed at least once\n                throw e;\n            }\n        }\n\n        return false;\n    }\n\n    public static void initializeIfPossible() {\n        if (jdk6OrLater) {\n            initializeIfNeeded();\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassRedefiner.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.modules.agent;\n\nimport org.powermock.core.agent.JavaAgentClassRegister;\n\nimport java.util.Arrays;\n\npublic class PowerMockClassRedefiner {\n\n    public static void redefine(String[] classes, String[] packagesToIgnore, JavaAgentClassRegister agentClassRegister) {\n        PowerMockClassTransformer transformer = PowerMockAgent.getClasstransformer();\n        transformer.setClassesToTransform(Arrays.asList(classes));\n        transformer.setPackagesToIgnore(Arrays.asList(packagesToIgnore));\n        transformer.setJavaAgentClassRegister(agentClassRegister);\n\n        try {\n            for (int i = classes.length - 1; i >= 0; i--) {\n                String className = classes[i];\n                Class<?> clazz;\n                try {\n                    clazz = Class.forName(className);\n\n                    PowerMockAgent.instrumentation().retransformClasses(clazz);\n                } catch (Exception e) {\n                    throw new RuntimeException(e);\n                }\n            }\n        } finally {\n            transformer.resetPackagesToIgnore();\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassTransformer.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.modules.agent;\n\nimport javassist.ClassPool;\nimport javassist.CtClass;\nimport org.powermock.core.agent.JavaAgentClassRegister;\nimport org.powermock.core.transformers.ClassWrapper;\nimport org.powermock.core.transformers.ClassWrapperFactory;\nimport org.powermock.core.transformers.MockTransformerChain;\nimport org.powermock.core.transformers.TransformStrategy;\nimport org.powermock.core.transformers.javassist.JavassistMockTransformerChainFactory;\nimport org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.lang.instrument.ClassFileTransformer;\nimport java.lang.instrument.IllegalClassFormatException;\nimport java.security.ProtectionDomain;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Set;\n\nclass PowerMockClassTransformer extends AbstractClassTransformer implements ClassFileTransformer {\n    \n    private static final MockTransformerChain MOCK_TRANSFORMER_CHAIN = new JavassistMockTransformerChainFactory()\n                                                                           .createDefaultChain(TransformStrategy.INST_REDEFINE);\n    private final ClassWrapperFactory wrapperFactory;\n    private volatile Set<String> classesToTransform;\n    private volatile JavaAgentClassRegister javaAgentClassRegister;\n    \n    PowerMockClassTransformer() {\n        super();\n        wrapperFactory = new JavaAssistClassWrapperFactory();\n    }\n    \n    public void setClassesToTransform(Collection<String> classesToTransform) {\n        this.classesToTransform = new HashSet<String>(classesToTransform);\n    }\n    \n    public void setJavaAgentClassRegister(JavaAgentClassRegister javaAgentClassRegister) {\n        this.javaAgentClassRegister = javaAgentClassRegister;\n    }\n    \n    public byte[] transform(\n                               ClassLoader loader, String className,\n                               Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer\n    ) throws IllegalClassFormatException {\n        \n        if (loader == null || shouldIgnore(className)) {\n            return null;\n        }\n        try {\n            String normalizedClassName = className.replace(\"/\", \".\");\n            if (classesToTransform != null && classesToTransform.contains(normalizedClassName)) {\n                CtClass ctClass = getCtClass(classfileBuffer);\n                \n                ctClass = transform(ctClass);\n\n                /*\n                 * ClassPool may cause huge memory consumption if the number of CtClass\n                 * objects becomes amazingly large (this rarely happens since Javassist\n                 * tries to reduce memory consumption in various ways). To avoid this\n                 * problem, you can explicitly remove an unnecessary CtClass object from\n                 * the ClassPool. If you call detach() on a CtClass object, then that\n                 * CtClass object is removed from the ClassPool.\n                 */\n                ctClass.detach();\n                \n                javaAgentClassRegister.registerClass(loader, normalizedClassName);\n                \n                return ctClass.toBytecode();\n            }\n            \n            return null;\n        } catch (Exception e) {\n            throw new RuntimeException(\"Failed to redefine class \" + className, e);\n        }\n    }\n    \n    private CtClass getCtClass(final byte[] classfileBuffer) throws IOException {\n        final CtClass ctClass;\n        \n        ByteArrayInputStream is = new ByteArrayInputStream(classfileBuffer);\n        try {\n            ctClass = ClassPool.getDefault().makeClass(is);\n        } finally {\n            is.close();\n        }\n        return ctClass;\n    }\n    \n    private CtClass transform(CtClass ctClass) throws Exception {\n        ClassWrapper<CtClass> wrapped = wrapperFactory.wrap(ctClass);\n        wrapped = MOCK_TRANSFORMER_CHAIN.transform(wrapped);\n        return wrapped.unwrap();\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/JavaAgentClassRegisterImpl.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.modules.agent.support;\n\nimport org.powermock.core.agent.JavaAgentClassRegister;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n *  Basic not thread-safety implementation of  the  {@link JavaAgentClassRegister}\n */\npublic class JavaAgentClassRegisterImpl implements JavaAgentClassRegister {\n\n    private final Map<ClassLoader, Set<String>> modifiedClasses;\n\n    public JavaAgentClassRegisterImpl() {\n        modifiedClasses = new HashMap<ClassLoader, Set<String>>();\n    }\n\n    @Override\n    public boolean isModifiedByAgent(ClassLoader classLoader, String className) {\n        return modifiedClasses.containsKey(classLoader) && modifiedClasses.get(classLoader).contains(className);\n    }\n\n    @Override\n    public void registerClass(ClassLoader loader, String className) {\n\n        Set<String> names = modifiedClasses.get(loader);\n        if (names == null){\n            names = new HashSet<String>();\n            modifiedClasses.put(loader, names);\n        }\n\n        names.add(className);\n\n    }\n\n    @Override\n    public void clear() {\n        modifiedClasses.clear();\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/PowerMockAgentTestInitializer.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.agent.support;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.agent.JavaAgentClassRegister;\nimport org.powermock.modules.agent.PowerMockClassRedefiner;\nimport org.powermock.tests.utils.impl.MockPolicyInitializerImpl;\nimport org.powermock.tests.utils.impl.PowerMockIgnorePackagesExtractorImpl;\nimport org.powermock.tests.utils.impl.PrepareForTestExtractorImpl;\nimport org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl;\n\npublic class PowerMockAgentTestInitializer {\n\n    public static void initialize(Class<?> testClass, JavaAgentClassRegister agentClassRegister) {\n        /*\n         * For extra safety clear the MockitoRepository.\n\t\t */\n        MockRepository.clear();\n\n        redefineClasses(testClass, agentClassRegister);\n\n        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();\n\n        new MockPolicyInitializerImpl(testClass).initialize(contextClassLoader);\n    }\n\n    private static void redefineClasses(Class<?> testClass, JavaAgentClassRegister agentClassRegister) {\n        final String[] packagesToIgnore = new PowerMockIgnorePackagesExtractorImpl().getPackagesToIgnore(testClass);\n\n        redefineClassesToPrepare(testClass, packagesToIgnore, agentClassRegister);\n        redefineClassesToSuppress(testClass, packagesToIgnore, agentClassRegister);\n    }\n\n    private static void redefineClassesToSuppress(Class<?> testClass, String[] packagesToIgnore,\n                                                  JavaAgentClassRegister agentClassRegister) {\n        final String[] classesToSuppress = new StaticConstructorSuppressExtractorImpl().getTestClasses(testClass);\n        redefine(classesToSuppress, packagesToIgnore, agentClassRegister);\n    }\n\n    private static void redefineClassesToPrepare(Class<?> testClass, String[] packagesToIgnore,\n                                                 JavaAgentClassRegister agentClassRegister) {\n        final String[] classesToPrepare = new PrepareForTestExtractorImpl(true).getTestClasses(testClass);\n        redefine(classesToPrepare, packagesToIgnore, agentClassRegister);\n    }\n\n    private static void redefine(String[] classes, String[] packagesToIgnore,\n                                 JavaAgentClassRegister agentClassRegister) {\n        PowerMockClassRedefiner.redefine(classes, packagesToIgnore, agentClassRegister);\n    }\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java",
    "content": "/*\n * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\npackage sun.tools.attach;\n\nimport com.sun.tools.attach.AgentLoadException;\nimport com.sun.tools.attach.AttachNotSupportedException;\nimport com.sun.tools.attach.spi.AttachProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/*\n * Bsd implementation of HotSpotVirtualMachine\n */\npublic class BsdVirtualMachine extends HotSpotVirtualMachine {\n    // \"tmpdir\" is used as a global well-known location for the files\n    // .java_pid<pid>. and .attach_pid<pid>. It is important that this\n    // location is the same for all processes, otherwise the tools\n    // will not be able to find all Hotspot processes.\n    // This is intentionally not the same as java.io.tmpdir, since\n    // the latter can be changed by the user.\n    // Any changes to this needs to be synchronized with HotSpot.\n    private static final String tmpdir;\n\n    // The patch to the socket file created by the target VM\n    String path;\n\n    /**\n     * Attaches to the target VM\n     */\n    public BsdVirtualMachine(AttachProvider provider, String vmid)\n        throws AttachNotSupportedException, IOException\n    {\n        super(provider, vmid);\n\n        // This provider only understands pids\n        int pid;\n        try {\n            pid = Integer.parseInt(vmid);\n        } catch (NumberFormatException x) {\n            throw new AttachNotSupportedException(\"Invalid process identifier\");\n        }\n\n        // Find the socket file. If not found then we attempt to start the\n        // attach mechanism in the target VM by sending it a QUIT signal.\n        // Then we attempt to find the socket file again.\n        path = findSocketFile(pid);\n        if (path == null) {\n            File f = new File(tmpdir, \".attach_pid\" + pid);\n            createAttachFile(f.getPath());\n            try {\n                sendQuitTo(pid);\n\n                // give the target VM time to start the attach mechanism\n                int i = 0;\n                long delay = 200;\n                int retries = (int)(attachTimeout() / delay);\n                do {\n                    try {\n                        Thread.sleep(delay);\n                    } catch (InterruptedException x) { }\n                    path = findSocketFile(pid);\n                    i++;\n                } while (i <= retries && path == null);\n                if (path == null) {\n                    throw new AttachNotSupportedException(\n                        \"Unable to open socket file: target process not responding \" +\n                        \"or HotSpot VM not loaded\");\n                }\n            } finally {\n                f.delete();\n            }\n        }\n\n        // Check that the file owner/permission to avoid attaching to\n        // bogus process\n        checkPermissions(path);\n\n        // Check that we can connect to the process\n        // - this ensures we throw the permission denied error now rather than\n        // later when we attempt to enqueue a command.\n        int s = socket();\n        try {\n            connect(s, path);\n        } finally {\n            close(s);\n        }\n    }\n\n    /**\n     * Detach from the target VM\n     */\n    @Override\n    public void detach() throws IOException {\n        synchronized (this) {\n            if (this.path != null) {\n                this.path = null;\n            }\n        }\n    }\n\n    // protocol version\n    private final static String PROTOCOL_VERSION = \"1\";\n\n    // known errors\n    private final static int ATTACH_ERROR_BADVERSION = 101;\n\n    /**\n     * Execute the given command in the target VM.\n     */\n    @Override\n    InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {\n        assert args.length <= 3;                // includes null\n\n        // did we detach?\n        String p;\n        synchronized (this) {\n            if (this.path == null) {\n                throw new IOException(\"Detached from target VM\");\n            }\n            p = this.path;\n        }\n\n        // create UNIX socket\n        int s = socket();\n\n        // connect to target VM\n        try {\n            connect(s, p);\n        } catch (IOException x) {\n            close(s);\n            throw x;\n        }\n\n        IOException ioe = null;\n\n        // connected - write request\n        // <ver> <cmd> <args...>\n        try {\n            writeString(s, PROTOCOL_VERSION);\n            writeString(s, cmd);\n\n            for (int i=0; i<3; i++) {\n                if (i < args.length && args[i] != null) {\n                    writeString(s, (String)args[i]);\n                } else {\n                    writeString(s, \"\");\n                }\n            }\n        } catch (IOException x) {\n            ioe = x;\n        }\n\n\n        // Create an input stream to read reply\n        SocketInputStream sis = new SocketInputStream(s);\n\n        // Read the command completion status\n        int completionStatus;\n        try {\n            completionStatus = readInt(sis);\n        } catch (IOException x) {\n            sis.close();\n            if (ioe != null) {\n                throw ioe;\n            } else {\n                throw x;\n            }\n        }\n\n        if (completionStatus != 0) {\n            sis.close();\n\n            // In the event of a protocol mismatch then the target VM\n            // returns a known error so that we can throw a reasonable\n            // error.\n            if (completionStatus == ATTACH_ERROR_BADVERSION) {\n                throw new IOException(\"Protocol mismatch with target VM\");\n            }\n\n            // Special-case the \"load\" command so that the right exception is\n            // thrown.\n            if (cmd.equals(\"load\")) {\n                throw new AgentLoadException(\"Failed to load agent library\");\n            } else {\n                throw new IOException(\"Command failed in target VM\");\n            }\n        }\n\n        // Return the input stream so that the command output can be read\n        return sis;\n    }\n\n    /*\n     * InputStream for the socket connection to get target VM\n     */\n    private class SocketInputStream extends InputStream {\n        int s;\n\n        public SocketInputStream(int s) {\n            this.s = s;\n        }\n\n        @Override\n        public synchronized int read() throws IOException {\n            byte b[] = new byte[1];\n            int n = this.read(b, 0, 1);\n            if (n == 1) {\n                return b[0] & 0xff;\n            } else {\n                return -1;\n            }\n        }\n\n        @Override\n        public synchronized int read(byte[] bs, int off, int len) throws IOException {\n            if ((off < 0) || (off > bs.length) || (len < 0) ||\n                ((off + len) > bs.length) || ((off + len) < 0)) {\n                throw new IndexOutOfBoundsException();\n            } else if (len == 0)\n                return 0;\n\n            return BsdVirtualMachine.read(s, bs, off, len);\n        }\n\n        @Override\n        public void close() throws IOException {\n            BsdVirtualMachine.close(s);\n        }\n    }\n\n    // Return the socket file for the given process.\n    // Checks temp directory for .java_pid<pid>.\n    private String findSocketFile(int pid) {\n        String fn = \".java_pid\" + pid;\n        File f = new File(tmpdir, fn);\n        return f.exists() ? f.getPath() : null;\n    }\n\n    /*\n     * Write/sends the given to the target VM. String is transmitted in\n     * UTF-8 encoding.\n     */\n    private void writeString(int fd, String s) throws IOException {\n        if (s.length() > 0) {\n            byte b[];\n            try {\n                b = s.getBytes(\"UTF-8\");\n            } catch (java.io.UnsupportedEncodingException x) {\n                throw new InternalError();\n            }\n            BsdVirtualMachine.write(fd, b, 0, b.length);\n        }\n        byte b[] = new byte[1];\n        b[0] = 0;\n        write(fd, b, 0, 1);\n    }\n\n\n    //-- native methods\n\n    static native void sendQuitTo(int pid) throws IOException;\n\n    static native void checkPermissions(String path) throws IOException;\n\n    static native int socket() throws IOException;\n\n    static native void connect(int fd, String path) throws IOException;\n\n    static native void close(int fd) throws IOException;\n\n    static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;\n\n    static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;\n\n    static native void createAttachFile(String path);\n\n    static native String getTempDir();\n\n    static {\n        System.loadLibrary(\"attach\");\n        tmpdir = getTempDir();\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java",
    "content": "/*\n * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\n\npackage sun.tools.attach;\n\nimport com.sun.tools.attach.AgentInitializationException;\nimport com.sun.tools.attach.AgentLoadException;\nimport com.sun.tools.attach.VirtualMachine;\nimport com.sun.tools.attach.spi.AttachProvider;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Properties;\n\n/*\n * The HotSpot implementation of com.sun.tools.attach.VirtualMachine.\n */\n\npublic abstract class HotSpotVirtualMachine extends VirtualMachine {\n\n    HotSpotVirtualMachine(AttachProvider provider, String id) {\n        super(provider, id);\n    }\n\n    /*\n     * Load agent library\n     * If isAbsolute is true then the agent library is the absolute path\n     * to the library and thus will not be expanded in the target VM.\n     * if isAbsolute is false then the agent library is just a library\n     * name and it will be expended in the target VM.\n     */\n    private void loadAgentLibrary(String agentLibrary, boolean isAbsolute, String options)\n        throws AgentLoadException, AgentInitializationException, IOException\n    {\n        InputStream in = execute(\"load\",\n                                 agentLibrary,\n                                 isAbsolute ? \"true\" : \"false\",\n                                 options);\n        try {\n            int result = readInt(in);\n            if (result != 0) {\n                throw new AgentInitializationException(\"Agent_OnAttach failed\", result);\n            }\n        } finally {\n            in.close();\n\n        }\n    }\n\n    /*\n     * Load agent library - library name will be expanded in target VM\n     */\n    @Override\n    public void loadAgentLibrary(String agentLibrary, String options)\n        throws AgentLoadException, AgentInitializationException, IOException\n    {\n        loadAgentLibrary(agentLibrary, false, options);\n    }\n\n    /*\n     * Load agent - absolute path of library provided to target VM\n     */\n    @Override\n    public void loadAgentPath(String agentLibrary, String options)\n        throws AgentLoadException, AgentInitializationException, IOException\n    {\n        loadAgentLibrary(agentLibrary, true, options);\n    }\n\n    /*\n     * Load JPLIS agent which will load the agent JAR file and invoke\n     * the agentmain method.\n     */\n    @Override\n    public void loadAgent(String agent, String options)\n        throws AgentLoadException, AgentInitializationException, IOException\n    {\n        String args = agent;\n        if (options != null) {\n            args = args + \"=\" + options;\n        }\n        try {\n            loadAgentLibrary(\"instrument\", args);\n        } catch (AgentLoadException x) {\n            throw new InternalError(\"instrument library is missing in target VM\");\n        } catch (AgentInitializationException x) {\n            /*\n             * Translate interesting errors into the right exception and\n             * message (FIXME: create a better interface to the instrument\n             * implementation so this isn't necessary)\n             */\n            int rc = x.returnValue();\n            switch (rc) {\n                case JNI_ENOMEM:\n                    throw new AgentLoadException(\"Insuffient memory\");\n                case ATTACH_ERROR_BADJAR:\n                    throw new AgentLoadException(\"Agent JAR not found or no Agent-Class attribute\");\n                case ATTACH_ERROR_NOTONCP:\n                    throw new AgentLoadException(\"Unable to add JAR file to system class path\");\n                case ATTACH_ERROR_STARTFAIL:\n                    throw new AgentInitializationException(\"Agent JAR loaded but agent failed to initialize\");\n                default :\n                    throw new AgentLoadException(\"Failed to load agent - unknown reason: \" + rc);\n            }\n        }\n    }\n\n    /*\n     * The possible errors returned by JPLIS's agentmain\n     */\n    private static final int JNI_ENOMEM                 = -4;\n    private static final int ATTACH_ERROR_BADJAR        = 100;\n    private static final int ATTACH_ERROR_NOTONCP       = 101;\n    private static final int ATTACH_ERROR_STARTFAIL     = 102;\n\n\n    /*\n     * Send \"properties\" command to target VM\n     */\n    @Override\n    public Properties getSystemProperties() throws IOException {\n        InputStream in = null;\n        Properties props = new Properties();\n        try {\n            in = executeCommand(\"properties\");\n            props.load(in);\n        } finally {\n            if (in != null) in.close();\n        }\n        return props;\n    }\n\n    @Override\n    public Properties getAgentProperties() throws IOException {\n        InputStream in = null;\n        Properties props = new Properties();\n        try {\n            in = executeCommand(\"agentProperties\");\n            props.load(in);\n        } finally {\n            if (in != null) in.close();\n        }\n        return props;\n    }\n\n    // --- HotSpot specific methods ---\n\n    // same as SIGQUIT\n    public void localDataDump() throws IOException {\n        executeCommand(\"datadump\").close();\n    }\n\n    // Remote ctrl-break. The output of the ctrl-break actions can\n    // be read from the input stream.\n    public InputStream remoteDataDump(Object ... args) throws IOException {\n        return executeCommand(\"threaddump\", args);\n    }\n\n    // Remote heap dump. The output (error message) can be read from the\n    // returned input stream.\n    public InputStream dumpHeap(Object ... args) throws IOException {\n        return executeCommand(\"dumpheap\", args);\n    }\n\n    // Heap histogram (heap inspection in HotSpot)\n    public InputStream heapHisto(Object ... args) throws IOException {\n        return executeCommand(\"inspectheap\", args);\n    }\n\n    // set JVM command line flag\n    public InputStream setFlag(String name, String value) throws IOException {\n        return executeCommand(\"setflag\", name, value);\n    }\n\n    // print command line flag\n    public InputStream printFlag(String name) throws IOException {\n        return executeCommand(\"printflag\", name);\n    }\n\n    public InputStream executeJCmd(String command) throws IOException {\n        return executeCommand(\"jcmd\", command);\n    }\n\n    // -- Supporting methods\n\n\n    /*\n     * Execute the given command in the target VM - specific platform\n     * implementation must implement this.\n     */\n    abstract InputStream execute(String cmd, Object ... args)\n        throws AgentLoadException, IOException;\n\n    /*\n     * Convenience method for simple commands\n     */\n    private InputStream executeCommand(String cmd, Object ... args) throws IOException {\n        try {\n            return execute(cmd, args);\n        } catch (AgentLoadException x) {\n            throw new InternalError(\"Should not get here\");\n        }\n    }\n\n\n    /*\n     * Utility method to read an 'int' from the input stream. Ideally\n     * we should be using java.util.Scanner here but this implementation\n     * guarantees not to read ahead.\n     */\n    int readInt(InputStream in) throws IOException {\n        StringBuilder sb = new StringBuilder();\n\n        // read to \\n or EOF\n        int n;\n        byte buf[] = new byte[1];\n        do {\n            n = in.read(buf, 0, 1);\n            if (n > 0) {\n                char c = (char)buf[0];\n                if (c == '\\n') {\n                    break;                  // EOL found\n                } else {\n                    sb.append(c);\n                }\n            }\n        } while (n > 0);\n\n        if (sb.length() == 0) {\n            throw new IOException(\"Premature EOF\");\n        }\n\n        int value;\n        try {\n            value = Integer.parseInt(sb.toString());\n        } catch (NumberFormatException x) {\n            throw new IOException(\"Non-numeric value found - int expected\");\n        }\n        return value;\n    }\n\n    // -- attach timeout support\n\n    private static long defaultAttachTimeout = 5000;\n    private volatile long attachTimeout;\n\n    /*\n     * Return attach timeout based on the value of the sun.tools.attach.attachTimeout\n     * property, or the default timeout if the property is not set to a positive\n     * value.\n     */\n    final long attachTimeout() {\n        if (attachTimeout == 0) {\n            synchronized(this) {\n                if (attachTimeout == 0) {\n                    try {\n                        String s =\n                            System.getProperty(\"sun.tools.attach.attachTimeout\");\n                        attachTimeout = Long.parseLong(s);\n                    } catch (SecurityException se) {\n                    } catch (NumberFormatException ne) {\n                    }\n                    if (attachTimeout <= 0) {\n                       attachTimeout = defaultAttachTimeout;\n                    }\n                }\n            }\n        }\n        return attachTimeout;\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java",
    "content": "/*\n * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\npackage sun.tools.attach;\n\nimport com.sun.tools.attach.AgentLoadException;\nimport com.sun.tools.attach.AttachNotSupportedException;\nimport com.sun.tools.attach.spi.AttachProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/*\n * Linux implementation of HotSpotVirtualMachine\n */\npublic class LinuxVirtualMachine extends HotSpotVirtualMachine {\n    // \"/tmp\" is used as a global well-known location for the files\n    // .java_pid<pid>. and .attach_pid<pid>. It is important that this\n    // location is the same for all processes, otherwise the tools\n    // will not be able to find all Hotspot processes.\n    // Any changes to this needs to be synchronized with HotSpot.\n    private static final String tmpdir = \"/tmp\";\n\n    // Indicates if this machine uses the old LinuxThreads\n    static boolean isLinuxThreads;\n\n    // The patch to the socket file created by the target VM\n    String path;\n\n    /**\n     * Attaches to the target VM\n     */\n    public LinuxVirtualMachine(AttachProvider provider, String vmid)\n        throws AttachNotSupportedException, IOException\n    {\n        super(provider, vmid);\n\n        // This provider only understands pids\n        int pid;\n        try {\n            pid = Integer.parseInt(vmid);\n        } catch (NumberFormatException x) {\n            throw new AttachNotSupportedException(\"Invalid process identifier\");\n        }\n\n        // Find the socket file. If not found then we attempt to start the\n        // attach mechanism in the target VM by sending it a QUIT signal.\n        // Then we attempt to find the socket file again.\n        path = findSocketFile(pid);\n        if (path == null) {\n            File f = createAttachFile(pid);\n            try {\n                // On LinuxThreads each thread is a process and we don't have the\n                // pid of the VMThread which has SIGQUIT unblocked. To workaround\n                // this we get the pid of the \"manager thread\" that is created\n                // by the first call to pthread_create. This is parent of all\n                // threads (except the initial thread).\n                if (isLinuxThreads) {\n                    int mpid;\n                    try {\n                        mpid = getLinuxThreadsManager(pid);\n                    } catch (IOException x) {\n                        throw new AttachNotSupportedException(x.getMessage());\n                    }\n                    assert(mpid >= 1);\n                    sendQuitToChildrenOf(mpid);\n                } else {\n                    sendQuitTo(pid);\n                }\n\n                // give the target VM time to start the attach mechanism\n                int i = 0;\n                long delay = 200;\n                int retries = (int)(attachTimeout() / delay);\n                do {\n                    try {\n                        Thread.sleep(delay);\n                    } catch (InterruptedException x) { }\n                    path = findSocketFile(pid);\n                    i++;\n                } while (i <= retries && path == null);\n                if (path == null) {\n                    throw new AttachNotSupportedException(\n                        \"Unable to open socket file: target process not responding \" +\n                        \"or HotSpot VM not loaded\");\n                }\n            } finally {\n                f.delete();\n            }\n        }\n\n        // Check that the file owner/permission to avoid attaching to\n        // bogus process\n        checkPermissions(path);\n\n        // Check that we can connect to the process\n        // - this ensures we throw the permission denied error now rather than\n        // later when we attempt to enqueue a command.\n        int s = socket();\n        try {\n            connect(s, path);\n        } finally {\n            close(s);\n        }\n    }\n\n    /**\n     * Detach from the target VM\n     */\n    @Override\n    public void detach() throws IOException {\n        synchronized (this) {\n            if (this.path != null) {\n                this.path = null;\n            }\n        }\n    }\n\n    // protocol version\n    private final static String PROTOCOL_VERSION = \"1\";\n\n    // known errors\n    private final static int ATTACH_ERROR_BADVERSION = 101;\n\n    /**\n     * Execute the given command in the target VM.\n     */\n    @Override\n    InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {\n        assert args.length <= 3;                // includes null\n\n        // did we detach?\n        String p;\n        synchronized (this) {\n            if (this.path == null) {\n                throw new IOException(\"Detached from target VM\");\n            }\n            p = this.path;\n        }\n\n        // create UNIX socket\n        int s = socket();\n\n        // connect to target VM\n        try {\n            connect(s, p);\n        } catch (IOException x) {\n            close(s);\n            throw x;\n        }\n\n        IOException ioe = null;\n\n        // connected - write request\n        // <ver> <cmd> <args...>\n        try {\n            writeString(s, PROTOCOL_VERSION);\n            writeString(s, cmd);\n\n            for (int i=0; i<3; i++) {\n                if (i < args.length && args[i] != null) {\n                    writeString(s, (String)args[i]);\n                } else {\n                    writeString(s, \"\");\n                }\n            }\n        } catch (IOException x) {\n            ioe = x;\n        }\n\n\n        // Create an input stream to read reply\n        SocketInputStream sis = new SocketInputStream(s);\n\n        // Read the command completion status\n        int completionStatus;\n        try {\n            completionStatus = readInt(sis);\n        } catch (IOException x) {\n            sis.close();\n            if (ioe != null) {\n                throw ioe;\n            } else {\n                throw x;\n            }\n        }\n\n        if (completionStatus != 0) {\n            sis.close();\n\n            // In the event of a protocol mismatch then the target VM\n            // returns a known error so that we can throw a reasonable\n            // error.\n            if (completionStatus == ATTACH_ERROR_BADVERSION) {\n                throw new IOException(\"Protocol mismatch with target VM\");\n            }\n\n            // Special-case the \"load\" command so that the right exception is\n            // thrown.\n            if (cmd.equals(\"load\")) {\n                throw new AgentLoadException(\"Failed to load agent library\");\n            } else {\n                throw new IOException(\"Command failed in target VM\");\n            }\n        }\n\n        // Return the input stream so that the command output can be read\n        return sis;\n    }\n\n    /*\n     * InputStream for the socket connection to get target VM\n     */\n    private class SocketInputStream extends InputStream {\n        int s;\n\n        public SocketInputStream(int s) {\n            this.s = s;\n        }\n\n        @Override\n        public synchronized int read() throws IOException {\n            byte b[] = new byte[1];\n            int n = this.read(b, 0, 1);\n            if (n == 1) {\n                return b[0] & 0xff;\n            } else {\n                return -1;\n            }\n        }\n\n        @Override\n        public synchronized int read(byte[] bs, int off, int len) throws IOException {\n            if ((off < 0) || (off > bs.length) || (len < 0) ||\n                ((off + len) > bs.length) || ((off + len) < 0)) {\n                throw new IndexOutOfBoundsException();\n            } else if (len == 0)\n                return 0;\n\n            return LinuxVirtualMachine.read(s, bs, off, len);\n        }\n\n        @Override\n        public void close() throws IOException {\n            LinuxVirtualMachine.close(s);\n        }\n    }\n\n    // Return the socket file for the given process.\n    private String findSocketFile(int pid) {\n        File f = new File(tmpdir, \".java_pid\" + pid);\n        if (!f.exists()) {\n            return null;\n        }\n        return f.getPath();\n    }\n\n    // On Solaris/Linux a simple handshake is used to start the attach mechanism\n    // if not already started. The client creates a .attach_pid<pid> file in the\n    // target VM's working directory (or temp directory), and the SIGQUIT handler\n    // checks for the file.\n    private File createAttachFile(int pid) throws IOException {\n        String fn = \".attach_pid\" + pid;\n        String path = \"/proc/\" + pid + \"/cwd/\" + fn;\n        File f = new File(path);\n        try {\n            f.createNewFile();\n        } catch (IOException x) {\n            f = new File(tmpdir, fn);\n            f.createNewFile();\n        }\n        return f;\n    }\n\n    /*\n     * Write/sends the given to the target VM. String is transmitted in\n     * UTF-8 encoding.\n     */\n    private void writeString(int fd, String s) throws IOException {\n        if (s.length() > 0) {\n            byte b[];\n            try {\n                b = s.getBytes(\"UTF-8\");\n            } catch (java.io.UnsupportedEncodingException x) {\n                throw new InternalError();\n            }\n            LinuxVirtualMachine.write(fd, b, 0, b.length);\n        }\n        byte b[] = new byte[1];\n        b[0] = 0;\n        write(fd, b, 0, 1);\n    }\n\n\n    //-- native methods\n\n    static native boolean isLinuxThreads();\n\n    static native int getLinuxThreadsManager(int pid) throws IOException;\n\n    static native void sendQuitToChildrenOf(int pid) throws IOException;\n\n    static native void sendQuitTo(int pid) throws IOException;\n\n    static native void checkPermissions(String path) throws IOException;\n\n    static native int socket() throws IOException;\n\n    static native void connect(int fd, String path) throws IOException;\n\n    static native void close(int fd) throws IOException;\n\n    static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;\n\n    static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;\n\n    static {\n        System.loadLibrary(\"attach\");\n        isLinuxThreads = isLinuxThreads();\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/SolarisVirtualMachine.java",
    "content": "/*\n * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\npackage sun.tools.attach;\n\nimport com.sun.tools.attach.AgentLoadException;\nimport com.sun.tools.attach.AttachNotSupportedException;\nimport com.sun.tools.attach.spi.AttachProvider;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/*\n * Solaris implementation of HotSpotVirtualMachine.\n */\npublic class SolarisVirtualMachine extends HotSpotVirtualMachine {\n    // \"/tmp\" is used as a global well-known location for the files\n    // .java_pid<pid>. and .attach_pid<pid>. It is important that this\n    // location is the same for all processes, otherwise the tools\n    // will not be able to find all Hotspot processes.\n    // Any changes to this needs to be synchronized with HotSpot.\n    private static final String tmpdir = \"/tmp\";\n\n    // door descriptor;\n    private int fd = -1;\n\n    /**\n     * Attaches to the target VM\n     */\n    public SolarisVirtualMachine(AttachProvider provider, String vmid)\n        throws AttachNotSupportedException, IOException\n    {\n        super(provider, vmid);\n        // This provider only understands process-ids (pids).\n        int pid;\n        try {\n            pid = Integer.parseInt(vmid);\n        } catch (NumberFormatException x) {\n            throw new AttachNotSupportedException(\"invalid process identifier\");\n        }\n\n        // Opens the door file to the target VM. If the file is not\n        // found it might mean that the attach mechanism isn't started in the\n        // target VM so we attempt to start it and retry.\n        try {\n            fd = openDoor(pid);\n        } catch (FileNotFoundException fnf1) {\n            File f = createAttachFile(pid);\n            try {\n                // kill -QUIT will tickle target VM to check for the\n                // attach file.\n                sigquit(pid);\n\n                // give the target VM time to start the attach mechanism\n                int i = 0;\n                long delay = 200;\n                int retries = (int)(attachTimeout() / delay);\n                do {\n                    try {\n                        Thread.sleep(delay);\n                    } catch (InterruptedException x) { }\n                    try {\n                        fd = openDoor(pid);\n                    } catch (FileNotFoundException fnf2) { }\n                    i++;\n                } while (i <= retries && fd == -1);\n                if (fd == -1) {\n                    throw new AttachNotSupportedException(\n                        \"Unable to open door: target process not responding or \" +\n                        \"HotSpot VM not loaded\");\n                }\n            } finally {\n                f.delete();\n            }\n        }\n        assert fd >= 0;\n    }\n\n    /**\n     * Detach from the target VM\n     */\n    @Override\n    public void detach() throws IOException {\n        synchronized (this) {\n            if (fd != -1) {\n                close(fd);\n                fd = -1;\n            }\n        }\n    }\n\n    /**\n     * Execute the given command in the target VM.\n     */\n    @Override\n    InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {\n        assert args.length <= 3;                // includes null\n\n        // first check that we are still attached\n        int door;\n        synchronized (this) {\n            if (fd == -1) {\n                throw new IOException(\"Detached from target VM\");\n            }\n            door = fd;\n        }\n\n        // enqueue the command via a door call\n        int s = enqueue(door, cmd, args);\n        assert s >= 0;                          // valid file descriptor\n\n        // The door call returns a file descriptor (one end of a socket pair).\n        // Create an input stream around it.\n        SocketInputStream sis = new SocketInputStream(s);\n\n        // Read the command completion status\n        int completionStatus;\n        try {\n            completionStatus = readInt(sis);\n        } catch (IOException ioe) {\n            sis.close();\n            throw ioe;\n        }\n\n        // If non-0 it means an error but we need to special-case the\n        // \"load\" command to ensure that the right exception is thrown.\n        if (completionStatus != 0) {\n            sis.close();\n            if (cmd.equals(\"load\")) {\n                throw new AgentLoadException(\"Failed to load agent library\");\n            } else {\n                throw new IOException(\"Command failed in target VM\");\n            }\n        }\n\n        // Return the input stream so that the command output can be read\n        return sis;\n    }\n\n    // InputStream over a socket\n    private class SocketInputStream extends InputStream {\n        int s;\n\n        public SocketInputStream(int s) {\n            this.s = s;\n        }\n\n        @Override\n        public synchronized int read() throws IOException {\n            byte b[] = new byte[1];\n            int n = this.read(b, 0, 1);\n            if (n == 1) {\n                return b[0] & 0xff;\n            } else {\n                return -1;\n            }\n        }\n\n        @Override\n        public synchronized int read(byte[] bs, int off, int len) throws IOException {\n            if ((off < 0) || (off > bs.length) || (len < 0) ||\n                ((off + len) > bs.length) || ((off + len) < 0)) {\n                throw new IndexOutOfBoundsException();\n            } else if (len == 0)\n                return 0;\n\n            return SolarisVirtualMachine.read(s, bs, off, len);\n        }\n\n        @Override\n        public void close() throws IOException {\n            SolarisVirtualMachine.close(s);\n        }\n    }\n\n    // The door is attached to .java_pid<pid> in the temporary directory.\n    private int openDoor(int pid) throws IOException {\n        String path = tmpdir + \"/.java_pid\" + pid;;\n        fd = open(path);\n\n        // Check that the file owner/permission to avoid attaching to\n        // bogus process\n        try {\n            checkPermissions(path);\n        } catch (IOException ioe) {\n            close(fd);\n            throw ioe;\n        }\n        return fd;\n    }\n\n    // On Solaris/Linux a simple handshake is used to start the attach mechanism\n    // if not already started. The client creates a .attach_pid<pid> file in the\n    // target VM's working directory (or temporary directory), and the SIGQUIT\n    // handler checks for the file.\n    private File createAttachFile(int pid) throws IOException {\n        String fn = \".attach_pid\" + pid;\n        String path = \"/proc/\" + pid + \"/cwd/\" + fn;\n        File f = new File(path);\n        try {\n            f.createNewFile();\n        } catch (IOException x) {\n            f = new File(tmpdir, fn);\n            f.createNewFile();\n        }\n        return f;\n    }\n\n    //-- native methods\n\n    static native int open(String path) throws IOException;\n\n    static native void close(int fd) throws IOException;\n\n    static native int read(int fd, byte buf[], int off, int buflen) throws IOException;\n\n    static native void checkPermissions(String path) throws IOException;\n\n    static native void sigquit(int pid) throws IOException;\n\n    // enqueue a command (and arguments) to the given door\n    static native int enqueue(int fd, String cmd, Object ... args)\n        throws IOException;\n\n    static {\n        System.loadLibrary(\"attach\");\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/WindowsVirtualMachine.java",
    "content": "/*\n * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.  Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\npackage sun.tools.attach;\n\nimport com.sun.tools.attach.AgentLoadException;\nimport com.sun.tools.attach.AttachNotSupportedException;\nimport com.sun.tools.attach.spi.AttachProvider;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Random;\n\npublic class WindowsVirtualMachine extends HotSpotVirtualMachine {\n\n    // the enqueue code stub (copied into each target VM)\n    private static byte[] stub;\n\n    private volatile long hProcess;     // handle to the process\n\n    public WindowsVirtualMachine(AttachProvider provider, String id)\n        throws AttachNotSupportedException, IOException\n    {\n        super(provider, id);\n\n        int pid;\n        try {\n            pid = Integer.parseInt(id);\n        } catch (NumberFormatException x) {\n            throw new AttachNotSupportedException(\"Invalid process identifier\");\n        }\n        hProcess = openProcess(pid);\n\n        // The target VM might be a pre-6.0 VM so we enqueue a \"null\" command\n        // which minimally tests that the enqueue function exists in the target\n        // VM.\n        try {\n            enqueue(hProcess, stub, null, null);\n        } catch (IOException x) {\n            throw new AttachNotSupportedException(x.getMessage());\n        }\n    }\n\n    @Override\n    public void detach() throws IOException {\n        synchronized (this) {\n            if (hProcess != -1) {\n                closeProcess(hProcess);\n                hProcess = -1;\n            }\n        }\n    }\n\n    @Override\n    InputStream execute(String cmd, Object ... args)\n        throws AgentLoadException, IOException\n    {\n        assert args.length <= 3;        // includes null\n\n        // create a pipe using a random name\n        int r = (new Random()).nextInt();\n        String pipename = \"\\\\\\\\.\\\\pipe\\\\javatool\" + r;\n        long hPipe = createPipe(pipename);\n\n        // check if we are detached - in theory it's possible that detach is invoked\n        // after this check but before we enqueue the command.\n        if (hProcess == -1) {\n            closePipe(hPipe);\n            throw new IOException(\"Detached from target VM\");\n        }\n\n        try {\n            // enqueue the command to the process\n            enqueue(hProcess, stub, cmd, pipename, args);\n\n            // wait for command to complete - process will connect with the\n            // completion status\n            connectPipe(hPipe);\n\n            // create an input stream for the pipe\n            PipedInputStream is = new PipedInputStream(hPipe);\n\n            // read completion status\n            int status = readInt(is);\n            if (status != 0) {\n                // special case the load command so that the right exception is thrown\n                if (cmd.equals(\"load\")) {\n                    throw new AgentLoadException(\"Failed to load agent library\");\n                } else {\n                    throw new IOException(\"Command failed in target VM\");\n                }\n            }\n\n            // return the input stream\n            return is;\n\n        } catch (IOException ioe) {\n            closePipe(hPipe);\n            throw ioe;\n        }\n    }\n\n    // An InputStream based on a pipe to the target VM\n    private class PipedInputStream extends InputStream {\n\n        private long hPipe;\n\n        public PipedInputStream(long hPipe) {\n            this.hPipe = hPipe;\n        }\n\n        @Override\n        public synchronized int read() throws IOException {\n            byte b[] = new byte[1];\n            int n = this.read(b, 0, 1);\n            if (n == 1) {\n                return b[0] & 0xff;\n            } else {\n                return -1;\n            }\n        }\n\n        @Override\n        public synchronized int read(byte[] bs, int off, int len) throws IOException {\n            if ((off < 0) || (off > bs.length) || (len < 0) ||\n                ((off + len) > bs.length) || ((off + len) < 0)) {\n                throw new IndexOutOfBoundsException();\n            } else if (len == 0)\n                return 0;\n\n            return WindowsVirtualMachine.readPipe(hPipe, bs, off, len);\n        }\n\n        @Override\n        public void close() throws IOException {\n            if (hPipe != -1) {\n                WindowsVirtualMachine.closePipe(hPipe);\n                hPipe = -1;\n           }\n        }\n    }\n\n\n    //-- native methods\n\n    static native void init();\n\n    static native byte[] generateStub();\n\n    static native long openProcess(int pid) throws IOException;\n\n    static native void closeProcess(long hProcess) throws IOException;\n\n    static native long createPipe(String name) throws IOException;\n\n    static native void closePipe(long hPipe) throws IOException;\n\n    static native void connectPipe(long hPipe) throws IOException;\n\n    static native int readPipe(long hPipe, byte buf[], int off, int buflen) throws IOException;\n\n    static native void enqueue(long hProcess, byte[] stub,\n        String cmd, String pipename, Object ... args) throws IOException;\n\n    static {\n        System.loadLibrary(\"attach\");\n        init();                                 // native initialization\n        stub = generateStub();                  // generate stub to copy into target process\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-javaagent/src/main/javadoc/resources/org,powermock/modules/agent/package.html",
    "content": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<HTML>\n  <HEAD>\n    <TITLE>PowerMock Java Agent package</TITLE>\n  </HEAD>\n  <BODY>\n    The PowerMock agent classes. The PowerMock agent solution is based on the excellent work of Rogério Liesenfeld, founder of JMockit. JMockit license:\n\n    The JMockit Testing Toolkit\n    Copyright (c) 2006-2011 Rogério Liesenfeld\n\n    Permission is hereby granted, free of charge, to any person obtaining\n    a copy of this software and associated documentation files (the\n    \"Software\"), to deal in the Software without restriction, including\n    without limitation the rights to use, copy, modify, merge, publish,\n    distribute, sublicense, and/or sell copies of the Software, and to\n    permit persons to whom the Software is furnished to do so, subject to\n    the following conditions:\n\n    The above copyright notice and this permission notice shall be\n    included in all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n  </BODY>\n</HTML>\n\n\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunner.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate;\nimport org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner;\nimport org.powermock.modules.junit4.common.internal.impl.JUnitVersion;\nimport org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner;\nimport org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl;\nimport org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl;\nimport org.powermock.modules.junit4.internal.impl.PowerMockJUnit49RunnerDelegateImpl;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\n\npublic class PowerMockRunner extends AbstractCommonPowerMockRunner {\n\n    public PowerMockRunner(Class<?> klass) throws Exception {\n        super(klass, getRunnerDelegateImplClass(klass));\n    }\n    \n    private static Class<? extends PowerMockJUnitRunnerDelegate> getRunnerDelegateImplClass(Class<?> klass) {\n        if (klass.isAnnotationPresent(PowerMockRunnerDelegate.class)\n                || Boolean.getBoolean(\"powermock.implicitDelegateAnnotation\")) {\n            return DelegatingPowerMockRunner.class;\n        }\n\n        Class<? extends PowerMockJUnitRunnerDelegate> concreteClass = PowerMockJUnit44RunnerDelegateImpl.class;\n        if(JUnitVersion.isGreaterThanOrEqualTo(\"4.9\")) {\n                   concreteClass = PowerMockJUnit49RunnerDelegateImpl.class;\n        } else if( JUnitVersion.isGreaterThanOrEqualTo(\"4.7\") ) {\n            concreteClass = PowerMockJUnit47RunnerDelegateImpl.class;\n        }\n        return concreteClass;\n    }\n\n    /**\n     * Clean up some state to avoid OOM issues\n     */\n    @Override\n    public void run(RunNotifier notifier) {\n        Description description = getDescription();\n        try {\n            super.run(notifier);\n        } finally {\n            Whitebox.setInternalState(description, \"fAnnotations\", new Annotation[]{});\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunnerDelegate.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4;\n\nimport org.junit.internal.builders.AllDefaultPossibilitiesBuilder;\nimport org.junit.internal.runners.JUnit38ClassRunner;\nimport org.junit.internal.runners.JUnit4ClassRunner;\nimport org.junit.runner.Description;\nimport org.junit.runner.Runner;\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runners.AllTests;\nimport org.junit.runners.JUnit4;\nimport org.junit.runners.model.InitializationError;\nimport org.junit.runners.model.RunnerBuilder;\nimport org.powermock.modules.junit4.common.internal.impl.JUnitVersion;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Inherited;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.lang.reflect.Method;\n\n@Target(ElementType.TYPE)\n@Documented\n@Retention(RetentionPolicy.RUNTIME)\n@Inherited\npublic @interface PowerMockRunnerDelegate {\n\n    Class<? extends Runner> value() default DefaultJUnitRunner.class;\n\n    public final class DefaultJUnitRunner extends Runner {\n\n        private final Runner wrappedDefaultRunner;\n\n        public DefaultJUnitRunner(Class<?> testClass) throws Throwable {\n            wrappedDefaultRunner = createDefaultRunner(testClass);\n        }\n\n        private static Runner createDefaultRunner(Class<?> testClass)\n        throws Throwable {\n            try {\n                Method suiteMethod = testClass.getMethod(\"suite\");\n                if (junit.framework.Test.class.isAssignableFrom(suiteMethod.getReturnType())) {\n                    return new AllTests(testClass);\n                } else {\n                    /* Continue below ... */\n                }\n            } catch (NoSuchMethodException thereIsNoSuiteMethod) {\n                /* Continue below ... */\n            }\n            if (junit.framework.TestCase.class.isAssignableFrom(testClass)) {\n                return new JUnit38ClassRunner(testClass);\n            } else if (JUnitVersion.isGreaterThanOrEqualTo(\"4.5\")) {\n                return SinceJUnit_4_5.createRunnerDelegate(testClass);\n            } else {\n                return new JUnit4ClassRunner(testClass);\n            }\n        }\n\n        @Override\n        public Description getDescription() {\n            return wrappedDefaultRunner.getDescription();\n        }\n\n        @Override\n        public void run(RunNotifier notifier) {\n            wrappedDefaultRunner.run(notifier);\n        }\n    }\n\n    /**\n     * Stuff that needs to be handled in a separate class, because it\n     * deals with API that did not exist before JUnit-4.5. Having this inside\n     * {@link DefaultJUnitRunner} would cause runtime error when JUnit-4.4\n     * or earlier is used.\n     */\n    public class SinceJUnit_4_5 {\n        static Runner createRunnerDelegate(Class<?> testClass) throws InitializationError {\n            return new JUnit4(testClass);\n        }\n        public static Class[] runnerAlternativeConstructorParams() {\n            return new Class[] {Class.class, RunnerBuilder.class};\n        }\n        public static Object newRunnerBuilder() {\n            return new AllDefaultPossibilitiesBuilder(false);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/DelegatingPowerMockRunner.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.internal.impl;\n\nimport org.junit.Test;\nimport org.junit.experimental.theories.Theory;\nimport org.junit.runner.Description;\nimport org.junit.runner.Runner;\nimport org.junit.runner.manipulation.Filter;\nimport org.junit.runner.manipulation.Filterable;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.core.testlisteners.GlobalNotificationBuildSupport;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate.SinceJUnit_4_5;\nimport org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate;\nimport org.powermock.modules.junit4.common.internal.impl.JUnitVersion;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\nimport org.powermock.tests.utils.impl.PowerMockTestNotifierImpl;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Callable;\n\npublic class DelegatingPowerMockRunner extends Runner\nimplements PowerMockJUnitRunnerDelegate, Filterable {\n\n    private final String testClassName;\n    private final Runner delegate;\n    private final ClassLoader testClassLoader;\n    private final Method[] testMethods;\n    private final PowerMockTestNotifier powerMockTestNotifier;\n\n    public DelegatingPowerMockRunner(Class<?> klass) throws Throwable {\n        this(klass, null);\n    }\n\n    public DelegatingPowerMockRunner(Class<?> klass, String[] methodsToRun)\n    throws Throwable {\n        this(klass, methodsToRun, null);\n    }\n\n    public DelegatingPowerMockRunner(\n            Class<?> klass, String[] methodsToRun, PowerMockTestListener[] listeners)\n    throws Exception {\n        testClassName = klass.getName();\n        delegate = createDelegate(klass);\n        testClassLoader = klass.getClassLoader();\n        testMethods = determineTestMethods(klass, methodsToRun);\n        powerMockTestNotifier = new PowerMockTestNotifierImpl(listeners == null ? new PowerMockTestListener[0] : listeners);\n    }\n\n    private static Method[] determineTestMethods(\n            Class<?> testClass, String[] testMethodNames) {\n        List<Method> testMethods = new ArrayList<Method>();\n        for (Method m : testClass.getMethods()) {\n            if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Theory.class)) {\n                testMethods.add(m);\n            }\n        }\n        if (testMethods.isEmpty()) {\n            for (String testMethodName : testMethodNames) {\n                try {\n                    testMethods.add(testClass.getMethod(testMethodName));\n                } catch (NoSuchMethodException ignore) {\n                    System.err.println(ignore.getMessage());\n                }\n            }\n        }\n        return testMethods.toArray(new Method[testMethods.size()]);\n    }\n\n    private static Runner createDelegate(final Class<?> testClass)\n    throws Exception {\n        /*\n         * Because of the mockito integration it seems like it is necessary to\n         * set context classloader during delegate creation ...\n         */\n        return withContextClassLoader(testClass.getClassLoader(),\n                new Callable<Runner>() {\n            @Override\n            public Runner call() throws Exception {\n                try {\n                    return Whitebox.invokeConstructor(\n                            testClass.isAnnotationPresent(PowerMockRunnerDelegate.class)\n                            ? testClass.getAnnotation(PowerMockRunnerDelegate.class).value()\n                            : PowerMockRunnerDelegate.DefaultJUnitRunner.class,\n                            new Class[] {Class.class},\n                            new Object[] {testClass});\n                } catch (ConstructorNotFoundException rootProblem) {\n                    if (testClass.isAnnotationPresent(PowerMockRunnerDelegate.class)\n                            && JUnitVersion.isGreaterThanOrEqualTo(\"4.5\")) {\n                        try {\n                            return Whitebox.invokeConstructor(testClass.getAnnotation(PowerMockRunnerDelegate.class).value(),\n                                    SinceJUnit_4_5.runnerAlternativeConstructorParams(),\n                                    new Object[] {\n                                        testClass,\n                                        SinceJUnit_4_5.newRunnerBuilder()\n                                    });\n                        } catch (ConstructorNotFoundException ignoredWorkAroundFailure) {\n                        }\n                    }\n                    throw rootProblem;\n                }\n            }\n        });\n    }\n\n    private static <T> T withContextClassLoader(\n            ClassLoader loader, Callable<T> callable) throws Exception {\n        final ClassLoader originalClassLoaderBackup =\n                Thread.currentThread().getContextClassLoader();\n        try {\n            Thread.currentThread().setContextClassLoader(loader);\n            return callable.call();\n        } finally {\n            Thread.currentThread().setContextClassLoader(originalClassLoaderBackup);\n        }\n    }\n\n    @Override\n    public void run(final RunNotifier notifier) {\n        try {\n            withContextClassLoader(testClassLoader, new Callable<Void>() {\n                @Override\n                public Void call() {\n                    PowerMockRunNotifier powerNotifier = new PowerMockRunNotifier(\n                            notifier, powerMockTestNotifier, testMethods);\n                    try {\n                        GlobalNotificationBuildSupport.prepareTestSuite(\n                                testClassName, powerNotifier);\n                        delegate.run(powerNotifier);\n                    } finally {\n                        GlobalNotificationBuildSupport\n                                .closePendingTestSuites(powerNotifier);\n                    }\n                    return null;\n                }\n            });\n        } catch (Exception cannotHappen) {\n            throw new Error(cannotHappen);\n        }\n    }\n\n    @Override\n    public Description getDescription() {\n        return delegate.getDescription();\n    }\n\n    @Override\n    public int getTestCount() {\n        return delegate.testCount();\n    }\n\n    @Override\n    public Class<?> getTestClass() {\n        return getDescription().getTestClass();\n    }\n\n    @Override\n    public void filter(Filter filter) throws NoTestsRemainException {\n        if (this.delegate instanceof Filterable) {\n            ((Filterable) this.delegate).filter(filter);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/NotificationBuilder.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.internal.impl;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.Failure;\nimport org.powermock.core.spi.testresult.Result;\nimport org.powermock.core.spi.testresult.TestMethodResult;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\nimport org.powermock.tests.utils.impl.MockPolicyInitializerImpl;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Method;\nimport java.util.IdentityHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * Stateful class that, from information from JUnit and test-classes,\n * can build and send notifications to PowerMockTestNotifier.\n */\nclass NotificationBuilder {\n\n    enum DetectedTestRunBehaviour {\n        PENDING,\n        START_FIRES_FIRST,\n        TEST_INSTANCE_CREATED_FIRST,\n        ALL_TESTINSTANCES_ARE_CREATED_FIRST,\n        TEST_INSTANCES_ARE_REUSED,\n        INCONSISTENT_BEHAVIOUR;\n    }\n\n    private static final Pattern methodDisplayNameRgx =\n            Pattern.compile(\"(^[^\\\\(\\\\[]++)|([^(]+(?=\\\\)))\");\n    private final Method[] testMethods;\n    private final List<?> pendingTestInstances;\n    private final PowerMockTestNotifier powerMockTestNotifier;\n    private DetectedTestRunBehaviour behaviour = DetectedTestRunBehaviour.PENDING;\n    private Description currentDescription;\n    private Object currentTestInstance;\n    private String testClassName;\n\n    private Object latestTestInstance;\n    private Method latestMethod;\n    private static final Object[] unsupportedMethodArgs = {};\n\n    private final Map<Object, List<Method>> methodsPerInstance =\n            new IdentityHashMap<Object, List<Method>>() {\n        @Override\n        public List<Method> get(Object key) {\n            if (!containsKey(key)) {\n                put(key, new LinkedList<Method>());\n            }\n            return super.get(key);\n        }\n    };\n\n    private final Map<Description, OngoingTestRun> ongoingTestRuns =\n            new IdentityHashMap<Description, OngoingTestRun>();\n\n    private class OngoingTestRun implements TestMethodResult {\n        final Description testDescription;\n        final Object testInstance;\n        final Method testMethod;\n        private Result result;\n\n        OngoingTestRun(Description testDescription, Object testInstance) {\n            this.testDescription = testDescription;\n            this.testInstance = testInstance;\n            this.testMethod = determineTestMethod(testDescription);\n            pendingTestInstances.remove(testInstance);\n            Class<?> testClass = testClass();\n            new MockPolicyInitializerImpl(testClass).initialize(testClass.getClassLoader());\n            powerMockTestNotifier.notifyBeforeTestMethod(\n                    testInstance, testMethod, unsupportedMethodArgs);\n            ongoingTestRuns.put(testDescription, this);            \n        }\n\n        final Class<?> testClass() {\n            if (null == testClassName) {\n                return testInstance.getClass();\n            } else {\n                try {\n                    return Class.forName(testClassName, false,\n                            testInstance.getClass().getClassLoader());\n                } catch (ClassNotFoundException ex) {\n                    return testInstance.getClass();\n                }\n            }\n        }\n\n        void report(Result result) {\n            if (null != this.result && Result.SUCCESSFUL == result\n                    || this.result == result) {\n                /* Already notified - ignore this duplication */\n                return;\n\n            } else if (null != this.result) {\n                new IllegalStateException(\n                        \"Will report an unexpected result-notification \" + result\n                        + \" after previously received notification \" + this.result)\n                        .printStackTrace();\n            }\n            this.result = result;\n            powerMockTestNotifier.notifyAfterTestMethod(\n                    testInstance, testMethod, unsupportedMethodArgs, this);\n        }\n\n        @Override\n        public Result getResult() {\n            return this.result;\n        }\n    }\n\n    public NotificationBuilder(Method[] testMethods,\n            PowerMockTestNotifier notifier,\n            List<?> pendingTestInstances) {\n        this.testMethods = testMethods;\n        this.pendingTestInstances = pendingTestInstances;\n        this.powerMockTestNotifier = notifier;\n    }\n\n    private Method determineTestMethod(Description d) {\n        Matcher matchMethodName = methodDisplayNameRgx\n                .matcher(d.getDisplayName());\n        matchMethodName.find();\n        String methodName = matchMethodName.group();\n        boolean latestTestMethodCanBeRepeated = false;\n        for (Method m : testMethods) {\n            if (m.getName().equals(methodName)) {\n                if (m == latestMethod) {\n                    latestTestMethodCanBeRepeated = true;\n                } else {\n                    return latestMethod = m;\n                }\n            }\n        }\n        if (latestTestMethodCanBeRepeated) {\n            return latestMethod;\n        } else {\n            new IllegalArgumentException(\n                    \"Unable to determine method-name from description=\"\n                    + d + \"; - ignored\").printStackTrace();\n            return null;\n        }\n    }\n\n    private Class<?> reloadParamType(\n            Class<?> testClass, Class<?> typeToReload) {\n        if (typeToReload.isPrimitive()\n                || testClass.getClassLoader() == typeToReload.getClassLoader()) {\n            return typeToReload;\n\n        } else if (typeToReload.isArray()) {\n            Class<?> newComponentType = reloadParamType(\n                    testClass, typeToReload.getComponentType());\n            if (newComponentType == typeToReload.getComponentType()) {\n                return typeToReload;\n            } else {\n                return Array.newInstance(newComponentType, 0).getClass();\n            }\n\n        } else {\n            try {\n                return Class.forName(typeToReload.getName(),\n                        true, testClass.getClassLoader());\n            } catch (ClassNotFoundException ex) {\n                throw new Error(ex);\n            }\n        }\n    }\n\n    private Method reloadMethod(Class<?> testClass, Method m) {\n        if (testClass.getClassLoader() == m.getDeclaringClass().getClassLoader()) {\n            return m;\n        } else if (!m.getDeclaringClass().getName()\n                .equals(testClass.getName())) {\n            return reloadMethod(testClass.getSuperclass(), m);\n        }\n        Class[] paramTypes = m.getParameterTypes();\n        for (int i = 0; i < paramTypes.length; ++i) {\n            paramTypes[i] = reloadParamType(testClass, paramTypes[i]);\n        }\n        try {\n            return testClass.getDeclaredMethod(m.getName(), paramTypes);\n        } catch (NoSuchMethodException ex) {\n            throw new Error(ex);\n        }\n    }\n\n    void testSuiteStarted(Class<?> testClass) {\n        for (int i = 0; i < testMethods.length; ++i) {\n            testMethods[i] = reloadMethod(testClass, testMethods[i]);\n        }\n        powerMockTestNotifier.notifyBeforeTestSuiteStarted(testClass, testMethods);\n        this.testClassName = testClass.getName();\n    }\n\n    void testStartHasBeenFired(Description d) {\n        OngoingTestRun oldTestRun = ongoingTestRuns.get(d);\n        if (null != oldTestRun && null != oldTestRun.getResult()) {\n            throw new IllegalStateException(\n                    \"Fired testrun is already running: \" + d);\n        }\n        currentDescription = d;\n        switch (behaviour) {\n            case PENDING:\n                behaviour = DetectedTestRunBehaviour.START_FIRES_FIRST;\n            case START_FIRES_FIRST:\n                return;\n            case TEST_INSTANCE_CREATED_FIRST:\n                if (currentTestInstance == latestTestInstance) {\n                    behaviour = DetectedTestRunBehaviour.TEST_INSTANCES_ARE_REUSED;\n                }\n            case TEST_INSTANCES_ARE_REUSED:\n                latestTestInstance = currentTestInstance;\n                methodsPerInstance.get(currentTestInstance).add(\n                        new OngoingTestRun(d, currentTestInstance).testMethod);\n                return;\n            case ALL_TESTINSTANCES_ARE_CREATED_FIRST:\n                System.err.println(\n                        \"Notifications are not supported when all test-instances are created first!\");\n                return;\n            default:\n                throw new AssertionError();\n        }\n    }\n\n    void testInstanceCreated(Object newTestInstance) {\n        switch (behaviour) {\n            case PENDING:\n                behaviour = DetectedTestRunBehaviour.TEST_INSTANCE_CREATED_FIRST;\n                currentTestInstance = newTestInstance;\n                return ;\n            case TEST_INSTANCE_CREATED_FIRST:\n                if (methodsPerInstance.isEmpty()) {\n                    behaviour = DetectedTestRunBehaviour.ALL_TESTINSTANCES_ARE_CREATED_FIRST;\n                } else if (currentTestInstance == latestTestInstance) {\n                    currentTestInstance = newTestInstance;\n                } else {\n                    behaviour = DetectedTestRunBehaviour.INCONSISTENT_BEHAVIOUR;\n                }\n                return;\n            case ALL_TESTINSTANCES_ARE_CREATED_FIRST:\n            case INCONSISTENT_BEHAVIOUR:\n                System.err.println(\n                        \"Notifications are not supported for behaviour \" + behaviour);\n                return;\n            case START_FIRES_FIRST:\n                currentTestInstance = latestTestInstance = newTestInstance;\n                latestMethod = determineTestMethod(currentDescription);\n                methodsPerInstance.get(newTestInstance).add(\n                        new OngoingTestRun(currentDescription, newTestInstance).testMethod);\n                return;\n            default:\n                throw new AssertionError(\"Unknown behaviour: \" + behaviour);\n        }\n    }\n\n    void testIgnored(Description d) {\n        if (!notify(d, Result.IGNORED)\n                && DetectedTestRunBehaviour.TEST_INSTANCE_CREATED_FIRST == behaviour\n                && currentTestInstance != latestTestInstance) {\n            /*\n             * Workaround for some bad behaviour in JUnit-4.4 default runner, \n             * which creates a test-instance first, even for a test that is ignored!!\n             */\n            currentTestInstance = latestTestInstance;\n        }\n    }\n\n    void assumptionFailed(Description d) {\n        notify(d, Result.IGNORED);\n    }\n\n    void failure(Failure f) {\n        notify(f.getDescription(), Result.FAILED);\n    }\n\n    void testFinished(Description d) {\n        notify(d, Result.SUCCESSFUL);\n    }\n\n    /**\n     * @return true if notification concerns an ongoing testrun; otherwise false\n     *         when there is no test launched for the specified description\n     */\n    private boolean notify(Description d, Result result) {\n        OngoingTestRun testRun = ongoingTestRuns.get(d);\n        if (null == testRun) {\n//            System.err.println(\"Notification not enabled for \" + d);\n            return false;\n        } else {\n            testRun.report(result);\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit44RunnerDelegateImpl.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.internal.impl;\n\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\nimport org.junit.Before;\nimport org.junit.internal.runners.ClassRoadie;\nimport org.junit.internal.runners.InitializationError;\nimport org.junit.internal.runners.JUnit4ClassRunner;\nimport org.junit.internal.runners.MethodRoadie;\nimport org.junit.internal.runners.MethodValidator;\nimport org.junit.internal.runners.TestClass;\nimport org.junit.internal.runners.TestMethod;\nimport org.junit.runner.Description;\nimport org.junit.runner.Runner;\nimport org.junit.runner.manipulation.Filter;\nimport org.junit.runner.manipulation.Filterable;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runner.manipulation.Sortable;\nimport org.junit.runner.manipulation.Sorter;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.classloader.annotations.PrepareEverythingForTest;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate;\nimport org.powermock.modules.junit4.internal.impl.testcaseworkaround.PowerMockJUnit4MethodValidator;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\nimport org.powermock.tests.utils.impl.MockPolicyInitializerImpl;\nimport org.powermock.tests.utils.impl.PowerMockTestNotifierImpl;\nimport org.powermock.tests.utils.impl.PrepareForTestExtractorImpl;\nimport org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * <p>\n * A JUnit4 test runner that only runs a specified set of test methods in a test\n * class.\n * </p>\n * <p>\n * Many parts of this class are essentially a rip off from\n * {@link JUnit4ClassRunner} used in JUnit 4.4. It does however not extend this\n * class because we cannot let it perform the stuff it does in its constructor.\n * Another thing that different is that if an exception is thrown in the test we\n * add a tip to error message asking the user if they've not forgot to add a\n * class to test. Yet another difference is that this runner notifies the\n * PowerMock listeners of certain events.\n * </p>\n * @see JUnit4ClassRunner\n */\n\n@SuppressWarnings(\"deprecation\")\npublic class PowerMockJUnit44RunnerDelegateImpl extends Runner implements Filterable, Sortable, PowerMockJUnitRunnerDelegate {\n    private final List<Method> testMethods;\n    private final TestClass testClass;\n    private final PowerMockTestNotifier powerMockTestNotifier;\n\n    public PowerMockJUnit44RunnerDelegateImpl(Class<?> klass, String[] methodsToRun, PowerMockTestListener[] listeners) throws InitializationError {\n        this.powerMockTestNotifier = new PowerMockTestNotifierImpl(listeners == null ? new PowerMockTestListener[0] : listeners);\n        testClass = new TestClass(klass);\n        testMethods = getTestMethods(klass, methodsToRun);\n        validate();\n    }\n\n    public PowerMockJUnit44RunnerDelegateImpl(Class<?> klass, String[] methodsToRun) throws InitializationError {\n        this(klass, methodsToRun, null);\n    }\n\n    public PowerMockJUnit44RunnerDelegateImpl(Class<?> klass) throws InitializationError {\n        this(klass, null);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    protected final List<Method> getTestMethods(Class<?> klass, String[] methodsToRun) {\n        if (methodsToRun == null || methodsToRun.length == 0) {\n            // The getTestMethods of TestClass is not visible so we need to look\n            // it invoke it using reflection.\n            try {\n                return (List<Method>) Whitebox.invokeMethod(testClass, \"getTestMethods\");\n            } catch (Throwable e) {\n                throw new RuntimeException(e);\n            }\n        } else {\n            List<Method> foundMethods = new LinkedList<Method>();\n            Method[] methods = klass.getMethods();\n            for (Method method : methods) {\n                for (String methodName : methodsToRun) {\n                    if (method.getName().equals(methodName)) {\n                        foundMethods.add(method);\n                    }\n                }\n            }\n            return foundMethods;\n        }\n    }\n\n    protected final void validate() throws InitializationError {\n        if (!TestCase.class.isAssignableFrom(testClass.getJavaClass())) {\n            MethodValidator methodValidator = new PowerMockJUnit4MethodValidator(testClass);\n            methodValidator.validateMethodsForDefaultRunner();\n            methodValidator.assertValid();\n        }\n    }\n\n    @Override\n    public void run(final RunNotifier notifier) {\n        new ClassRoadie(notifier, testClass, getDescription(), new Runnable() {\n            @Override\n            public void run() {\n                runMethods(notifier);\n            }\n        }).runProtected();\n    }\n\n    protected void runMethods(final RunNotifier notifier) {\n        final StaticConstructorSuppressExtractorImpl staticConstructorSuppressExtractorImpl = new StaticConstructorSuppressExtractorImpl();\n        Class<?> testType = getTestClass();\n        final ClassLoader thisClassLoader = getClass().getClassLoader();\n        if (!thisClassLoader.equals(testType.getClassLoader())) {\n            /*\n             * The test is loaded from another classloader, this means that we\n             * cannot get the correct annotations if we don't load the class\n             * from the correct class loader\n             */\n            try {\n                testType = thisClassLoader.loadClass(testType.getName());\n            } catch (ClassNotFoundException e) {\n                // This should never happen\n                throw new RuntimeException(\"Internal error in PowerMock\", e);\n            }\n        }\n        for (Method method : testMethods) {\n            if (staticConstructorSuppressExtractorImpl.getTestClasses(method) == null) {\n                staticConstructorSuppressExtractorImpl.getTestClasses(testType);\n            }\n            invokeTestMethod(method, notifier);\n        }\n    }\n\n    @Override\n    public Description getDescription() {\n        Description spec = Description.createSuiteDescription(getName(), classAnnotations());\n        List<Method> testMethods = this.testMethods;\n        for (Method method : testMethods)\n            spec.addChild(methodDescription(method));\n        return spec;\n    }\n\n    protected Annotation[] classAnnotations() {\n        return getTestClass().getAnnotations();\n    }\n\n    protected String getName() {\n        return getTestWrappedClass().getName();\n    }\n\n    protected Object createTest() throws Exception {\n        return createTestInstance();\n    }\n\n    private Object createTestInstance() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n        final TestClass testWrappedClass = getTestWrappedClass();\n        Constructor<?> constructor = null;\n        final Class<?> javaClass = testWrappedClass.getJavaClass();\n        if (TestCase.class.isAssignableFrom(javaClass)) {\n            constructor = TestSuite.getTestConstructor(javaClass.asSubclass(TestCase.class));\n            if (constructor.getParameterTypes().length == 1) {\n                return constructor.newInstance(javaClass.getSimpleName());\n            }\n        } else {\n            constructor = testWrappedClass.getConstructor();\n        }\n        return constructor.newInstance();\n    }\n\n    protected void invokeTestMethod(final Method method, RunNotifier notifier) {\n        Description description = methodDescription(method);\n        final Object testInstance;\n        try {\n            testInstance = createTest();\n        } catch (InvocationTargetException e) {\n            testAborted(notifier, description, e.getTargetException());\n            return;\n        } catch (Exception e) {\n            testAborted(notifier, description, e);\n            return;\n        }\n\n        // Check if we extend from TestClass, in that case we must run the setUp\n        // and tearDown methods.\n        final boolean extendsFromTestCase = TestCase.class.isAssignableFrom(testClass.getJavaClass());\n\n        final TestMethod testMethod = wrapMethod(method);\n        createPowerMockRunner(testInstance, testMethod, notifier, description, extendsFromTestCase).run();\n    }\n\n    protected PowerMockJUnit44MethodRunner createPowerMockRunner(final Object testInstance, final TestMethod testMethod, RunNotifier notifier,\n                                                                 Description description, final boolean extendsFromTestCase) {\n        return new PowerMockJUnit44MethodRunner(testInstance, testMethod, notifier, description, extendsFromTestCase);\n    }\n\n    private void testAborted(RunNotifier notifier, Description description, Throwable e) {\n        notifier.fireTestStarted(description);\n        notifier.fireTestFailure(new Failure(description, e));\n        notifier.fireTestFinished(description);\n    }\n\n    protected TestMethod wrapMethod(Method method) {\n        return new TestMethod(method, testClass);\n    }\n\n    protected String testName(Method method) {\n        return method.getName();\n    }\n\n    protected Description methodDescription(Method method) {\n        return Description.createTestDescription(getTestWrappedClass().getJavaClass(), testName(method), testAnnotations(method));\n    }\n\n    protected Annotation[] testAnnotations(Method method) {\n        return method.getAnnotations();\n    }\n\n    @Override\n    public void filter(Filter filter) throws NoTestsRemainException {\n        for (Iterator<Method> iter = testMethods.iterator(); iter.hasNext(); ) {\n            Method method = iter.next();\n            if (!filter.shouldRun(methodDescription(method)))\n                iter.remove();\n        }\n        if (testMethods.isEmpty())\n            throw new NoTestsRemainException();\n    }\n\n    @Override\n    public void sort(final Sorter sorter) {\n        Collections.sort(testMethods, new Comparator<Method>() {\n            @Override\n            public int compare(Method o1, Method o2) {\n                return sorter.compare(methodDescription(o1), methodDescription(o2));\n            }\n        });\n    }\n\n    protected TestClass getTestWrappedClass() {\n        return testClass;\n    }\n\n    @Override\n    public int getTestCount() {\n        return testMethods.size();\n    }\n\n    @Override\n    public Class<?> getTestClass() {\n        return testClass.getJavaClass();\n    }\n\n    protected class PowerMockJUnit44MethodRunner extends MethodRoadie {\n        private final Object testInstance;\n        private final boolean extendsFromTestCase;\n        protected final TestMethod testMethod;\n\n        protected PowerMockJUnit44MethodRunner(Object testInstance, TestMethod method, RunNotifier notifier, Description description,\n                                               boolean extendsFromTestCase) {\n            super(testInstance, method, notifier, description);\n            this.testInstance = testInstance;\n            this.extendsFromTestCase = extendsFromTestCase;\n            this.testMethod = method;\n        }\n\n        @Override\n        public void runBeforesThenTestThenAfters(final Runnable test) {\n            executeTest(Whitebox.getInternalState(testMethod, Method.class), testInstance, test);\n        }\n\n        public void executeTest(final Method method, final Object testInstance, final Runnable test) {\n            // Initialize mock policies for each test\n            final ClassLoader classloader = this.getClass().getClassLoader();\n            final Thread currentThread = Thread.currentThread();\n            final ClassLoader originalClassLoader = currentThread.getContextClassLoader();\n            currentThread.setContextClassLoader(classloader);\n            new MockPolicyInitializerImpl(testClass.getJavaClass()).initialize(classloader);\n            powerMockTestNotifier.notifyBeforeTestMethod(testInstance, method, new Object[0]);\n            try {\n                super.runBeforesThenTestThenAfters(test);\n            } finally {\n                currentThread.setContextClassLoader(originalClassLoader);\n            }\n        }\n\n        @Override\n        protected void runTestMethod() {\n            try {\n                try {\n                    if (extendsFromTestCase) {\n                        final Method setUp = Whitebox.getMethod(testInstance.getClass(), \"setUp\");\n                        if (!setUp.isAnnotationPresent(Before.class)) {\n                            Whitebox.invokeMethod(testInstance, \"setUp\");\n                        }\n                    }\n                    testMethod.invoke(testInstance);\n                    if (Whitebox.invokeMethod(testMethod, \"expectsException\")) {\n                        addFailure(new AssertionError(\"Expected exception: \" + getExpectedExceptionName(testMethod)));\n                    }\n                } catch (InvocationTargetException e) {\n                    handleInvocationTargetException(testMethod, e);\n                } catch (Throwable e) {\n                    addFailure(e);\n                } finally {\n                    if (extendsFromTestCase) {\n                        try {\n                            Whitebox.invokeMethod(testInstance, \"tearDown\");\n                        } catch (Throwable tearingDown) {\n                            addFailure(tearingDown);\n                        }\n                    }\n                }\n            } catch (Throwable e) {\n                throw new RuntimeException(\"Internal error in PowerMock.\", e);\n            }\n        }\n\n        private void handleInvocationTargetException(final TestMethod testMethod, InvocationTargetException e) throws Exception {\n            Throwable actual = e.getTargetException();\n            while (actual instanceof InvocationTargetException) {\n                actual = ((InvocationTargetException) actual).getTargetException();\n            }\n            handleException(testMethod, actual);\n        }\n\n        protected void handleException(final TestMethod testMethod, Throwable actualFailure) {\n            try {\n                final String throwableName = actualFailure.getClass().getName();\n                if (throwableName.equals(\"org.junit.internal.AssumptionViolatedException\") || throwableName.startsWith(\"org.junit.Assume$AssumptionViolatedException\")) {\n                    return;\n                } else if (!(Boolean) Whitebox.invokeMethod(testMethod, \"expectsException\")) {\n                    final String className = actualFailure.getStackTrace()[0].getClassName();\n                    final Class<?> testClassAsJavaClass = testClass.getJavaClass();\n                    if (actualFailure instanceof NullPointerException\n                            && !testClassAsJavaClass.getName().equals(className)\n                            && !className.startsWith(\"java.lang\")\n                            && !className.startsWith(\"org.powermock\")\n                            && !className.startsWith(\"org.junit\")\n                            && !new PrepareForTestExtractorImpl().isPrepared(testClassAsJavaClass, className)\n                            && !testClassAsJavaClass.isAnnotationPresent(PrepareEverythingForTest.class)\n                            && !new MockPolicyInitializerImpl(testClassAsJavaClass.isAnnotationPresent(MockPolicy.class) ? testClassAsJavaClass\n                            .getAnnotation(MockPolicy.class).value() : null).isPrepared(className)) {\n                        Whitebox.setInternalState(actualFailure, \"detailMessage\", \"Perhaps the class \" + className + \" must be prepared for test?\",\n                                Throwable.class);\n                    }\n                    addFailure(actualFailure);\n                } else if (Whitebox.invokeMethod(testMethod, \"isUnexpected\", actualFailure)) {\n                    String message = \"Unexpected exception, expected<\" + getExpectedExceptionName(testMethod) + \"> but was<\"\n                            + actualFailure.getClass().getName() + \">\";\n                    addFailure(new Exception(message, actualFailure));\n                }\n\n            } catch (Exception e) {\n                throw new RuntimeException(\"PowerMock internal error: Should never throw exception at this level\", e);\n            }\n        }\n\n        @SuppressWarnings(\"unchecked\")\n        private String getExpectedExceptionName(TestMethod fTestMethod) throws Exception {\n            return ((Class<? extends Throwable>) Whitebox.invokeMethod(fTestMethod, \"getExpectedException\")).getName();\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit47RunnerDelegateImpl.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.internal.impl;\n\nimport org.junit.Rule;\nimport org.junit.internal.runners.InitializationError;\nimport org.junit.internal.runners.TestMethod;\nimport org.junit.rules.MethodRule;\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\n/**\n * Extends the functionality of {@link PowerMockJUnit44RunnerDelegateImpl} to\n * enable the usage of rules.\n */\n@SuppressWarnings(\"deprecation\")\npublic class PowerMockJUnit47RunnerDelegateImpl extends PowerMockJUnit44RunnerDelegateImpl {\n    public boolean hasRules;\n\n    public PowerMockJUnit47RunnerDelegateImpl(Class<?> klass, String[] methodsToRun, PowerMockTestListener[] listeners) throws InitializationError {\n        super(klass, methodsToRun, listeners);\n    }\n\n    public PowerMockJUnit47RunnerDelegateImpl(Class<?> klass, String[] methodsToRun) throws InitializationError {\n        super(klass, methodsToRun);\n    }\n\n    public PowerMockJUnit47RunnerDelegateImpl(Class<?> klass) throws InitializationError {\n        super(klass);\n    }\n\n    @Override\n    protected PowerMockJUnit44MethodRunner createPowerMockRunner(final Object testInstance, final TestMethod testMethod, RunNotifier notifier,\n                                                                 Description description, final boolean extendsFromTestCase) {\n        return new PowerMockJUnit47MethodRunner(testInstance, testMethod, notifier, description, extendsFromTestCase);\n    }\n\n    protected class PowerMockJUnit47MethodRunner extends PowerMockJUnit44MethodRunner {\n\n        private Throwable potentialTestFailure;\n\n        protected PowerMockJUnit47MethodRunner(Object testInstance, TestMethod method, RunNotifier notifier, Description description,\n                                               boolean extendsFromTestCase) {\n            super(testInstance, method, notifier, description, extendsFromTestCase);\n        }\n\n        @Override\n        public void executeTest(final Method method, final Object testInstance, final Runnable test) {\n            // We change the context classloader to the current CL in order for the Mockito\n            // framework to load it's plugins (such as MockMaker) correctly.\n            final ClassLoader originalCL = Thread.currentThread().getContextClassLoader();\n            Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());\n            final Set<Field> rules;\n            try {\n                rules = Whitebox.getFieldsAnnotatedWith( testInstance, Rule.class );\n            } finally {\n                Thread.currentThread().setContextClassLoader(originalCL);\n            }\n            hasRules = !rules.isEmpty();\n            Statement statement = createStatement(method, testInstance, test, rules);\n            evaluateStatement(statement);\n        }\n\n        private Statement createStatement(Method method, Object testInstance, Runnable test, Set<Field> rules) {\n            Statement statement = new TestExecutorStatement(test, testInstance, method);\n            for (Field field : rules) {\n                try {\n                    statement = applyRuleToLastStatement(method,\n                            testInstance, field, statement);\n                } catch (Throwable e) {\n                    super.handleException(testMethod, e);\n                }\n            }\n            return statement;\n        }\n\n        protected Statement applyRuleToLastStatement(final Method method, final Object testInstance, Field field,\n                                                     final Statement lastStatement) throws IllegalAccessException {\n            MethodRule rule = (MethodRule) field.get(testInstance);\n            Statement statement = rule.apply(lastStatement, new FrameworkMethod(method), testInstance);\n            return statement;\n        }\n\n        private void evaluateStatement(Statement statement) {\n            try {\n                statement.evaluate();\n            } catch (Throwable e) {\n                //No rule could handle the exception thus we need to add it as a failure.\n                super.handleException(testMethod, potentialTestFailure == null ? e : potentialTestFailure);\n            }\n        }\n\n        /**\n         * Since a JUnit 4.7 rule may potentially deal with \"unexpected\"\n         * exceptions we cannot handle the exception before the rule has been\n         * completely evaluated. Thus we just store the exception here and\n         * rethrow it after the test method has finished executing. In that way\n         * the rule may get a chance to handle the exception appropriately.\n         */\n        @Override\n        protected void handleException(TestMethod testMethod, Throwable actualFailure) {\n            if (hasRules) {\n                potentialTestFailure = actualFailure;\n            } else {\n                super.handleException(testMethod, actualFailure);\n            }\n        }\n\n        private void executeTestInSuper(final Method method, final Object testInstance, final Runnable test) {\n            super.executeTest(method, testInstance, test);\n        }\n\n        private final class TestExecutorStatement extends Statement {\n            private final Runnable test;\n            private final Object testInstance;\n            private final Method method;\n\n            private TestExecutorStatement(Runnable test, Object testInstance, Method method) {\n                this.test = test;\n                this.testInstance = testInstance;\n                this.method = method;\n            }\n\n            @Override\n            public void evaluate() throws Throwable {\n                executeTestInSuper(method, testInstance, test);\n                if (potentialTestFailure != null) {\n                    // Rethrow the potential failure caught in the test.\n                    throw potentialTestFailure;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit49RunnerDelegateImpl.java",
    "content": "package org.powermock.modules.junit4.internal.impl;\n\n\nimport org.junit.internal.runners.InitializationError;\nimport org.junit.internal.runners.TestMethod;\nimport org.junit.rules.MethodRule;\nimport org.junit.rules.TestRule;\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runners.model.Statement;\nimport org.powermock.core.spi.PowerMockTestListener;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\n\n/**\n * Extends the functionality of {@link PowerMockJUnit47RunnerDelegateImpl} to enable the usage of\n * {@link TestRule}.\n */\n@SuppressWarnings( \"deprecation\" )\npublic class PowerMockJUnit49RunnerDelegateImpl extends PowerMockJUnit47RunnerDelegateImpl {\n\n    public PowerMockJUnit49RunnerDelegateImpl( Class<?> klass, String[] methodsToRun, PowerMockTestListener[] listeners ) throws InitializationError {\n        super( klass, methodsToRun, listeners );\n    }\n\n    public PowerMockJUnit49RunnerDelegateImpl( Class<?> klass, String[] methodsToRun ) throws InitializationError {\n        super( klass, methodsToRun );\n    }\n\n    public PowerMockJUnit49RunnerDelegateImpl( Class<?> klass ) throws InitializationError {\n        super( klass );\n    }\n\n    @Override\n    protected PowerMockJUnit47MethodRunner createPowerMockRunner( final Object testInstance,\n                                                                  final TestMethod testMethod,\n                                                                  RunNotifier notifier,\n                                                                  Description description,\n                                                                  final boolean extendsFromTestCase ) {\n        return new PowerMockJUnit49MethodRunner( testInstance, testMethod, notifier, description, extendsFromTestCase );\n    }\n\n    protected class PowerMockJUnit49MethodRunner extends PowerMockJUnit47MethodRunner {\n\n        private Description description;\n\n        protected PowerMockJUnit49MethodRunner( Object testInstance,\n                                                TestMethod method,\n                                                RunNotifier notifier,\n                                                Description description,\n                                                boolean extendsFromTestCase ) {\n            super( testInstance, method, notifier, description, extendsFromTestCase );\n            this.description = description;\n        }\n\n        @Override\n        protected Statement applyRuleToLastStatement(final Method method, final Object testInstance, Field field,\n                final Statement lastStatement) throws IllegalAccessException {\n            final Object fieldValue = field.get(testInstance);\n            final Statement statement;\n            if (fieldValue instanceof MethodRule) {\n                // the MethodRule is known by junit 4.9 -> delegate to super-class\n                statement = super.applyRuleToLastStatement(method, testInstance, field, lastStatement);\n            } else if (fieldValue instanceof TestRule){\n                TestRule rule = (TestRule) fieldValue;\n                statement = rule.apply(lastStatement, description);\n            } else {\n                throw new IllegalStateException(\"Can only handle MethodRule and TestRule\");\n            }\n            return statement;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifier.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.internal.impl;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunListener;\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runner.notification.StoppedByUserException;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.core.testlisteners.GlobalNotificationBuildSupport;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\n\nimport java.lang.reflect.Method;\nimport java.util.LinkedList;\n\nimport static org.powermock.reflect.Whitebox.invokeMethod;\n\n/**\n * Wraps JUnit's RunNotifier to make sure that the PowerMock-specific\n * instances of {@link PowerMockTestListener} will also be informed.\n * It is stateful and (hopefully) thread-safe.\n *\n * @see PowerMockTestListener\n */\nclass PowerMockRunNotifier extends RunNotifier\nimplements GlobalNotificationBuildSupport.Callback {\n\n    private Class<?> suiteClass = null;\n    private final Thread motherThread = Thread.currentThread();\n    private final RunNotifier junitRunNotifier;\n    private final PowerMockTestNotifier powerMockTestNotifier;\n    private final Method[] testMethods;\n    private final LinkedList<Object> pendingTestInstancesOnMotherThread =\n            new LinkedList<Object>();\n    private final ThreadLocal<NotificationBuilder> notificationBuilder =\n            new ThreadLocal<NotificationBuilder>() {\n        @Override\n        protected NotificationBuilder initialValue() {\n            return new NotificationBuilder(\n                    testMethods.clone(),\n                    powerMockTestNotifier,\n                    pendingTestInstancesOnMotherThread);\n        }\n    };\n\n    PowerMockRunNotifier(\n            RunNotifier junitRunNotifier,\n            PowerMockTestNotifier powerMockTestNotifier,\n            Method[] testMethods) {\n        this.junitRunNotifier = junitRunNotifier;\n        this.powerMockTestNotifier = powerMockTestNotifier;\n        this.testMethods = testMethods;\n    }\n\n    Class<?> getSuiteClass() {\n        return this.suiteClass;\n    }\n\n    @Override\n    public void suiteClassInitiated(Class<?> testClass) {\n        this.suiteClass = testClass;\n        notificationBuilder.get().testSuiteStarted(testClass);\n    }\n\n    @Override\n    public void testInstanceCreated(Object testInstance) {\n        if (Thread.currentThread() == motherThread) {\n            pendingTestInstancesOnMotherThread.add(testInstance);\n        }\n        notificationBuilder.get().testInstanceCreated(testInstance);\n    }\n\n    @Override\n    public void addListener(RunListener listener) {\n        invoke(\"addListener\", listener);\n    }\n\n    @Override\n    public void removeListener(RunListener listener) {\n        invoke(\"removeListener\", listener);\n    }\n\n    @Override\n    public void fireTestRunStarted(Description description) {\n        invoke(\"fireTestRunStarted\", description);\n    }\n\n    @Override\n    public void fireTestRunFinished(Result result) {\n        invoke(\"fireTestRunFinished\", result);\n    }\n\n    @Override\n    public void fireTestStarted(Description description)\n    throws StoppedByUserException {\n        invoke(\"fireTestStarted\", description);\n        notificationBuilder.get().testStartHasBeenFired(description);\n    }\n\n    @Override\n    public void fireTestFailure(Failure failure) {\n        notificationBuilder.get().failure(failure);\n        invoke(\"fireTestFailure\", failure);\n    }\n\n    @Override\n    public void fireTestAssumptionFailed(Failure failure) {\n        notificationBuilder.get().assumptionFailed(failure.getDescription());\n        invoke(\"fireTestAssumptionFailed\", failure);\n    }\n\n    @Override\n    public void fireTestIgnored(Description description) {\n        notificationBuilder.get().testIgnored(description);\n        invoke(\"fireTestIgnored\", description);\n    }\n\n    @Override\n    public void fireTestFinished(Description description) {\n        try {\n            notificationBuilder.get().testFinished(description);\n        } catch (Throwable failure) {\n            fireTestFailure(new Failure(description, failure));\n            return;\n        }\n        invoke(\"fireTestFinished\", description);\n    }\n\n    @Override\n    public void pleaseStop() {\n        invoke(\"pleaseStop\");\n    }\n\n    @Override\n    public void addFirstListener(RunListener listener) {\n        invoke(\"addFirstListener\", listener);\n    }\n\n    private void invoke(String methodName, Object... args) {\n        try {\n            invokeMethod(junitRunNotifier, methodName, args);\n        } catch (Exception ex) {\n            throw new RuntimeException(ex);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/testcaseworkaround/PowerMockJUnit4MethodValidator.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.internal.impl.testcaseworkaround;\n\nimport junit.framework.TestCase;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.internal.runners.MethodValidator;\nimport org.junit.internal.runners.TestClass;\nimport org.powermock.modules.junit4.common.internal.impl.JUnitVersion;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * A custom {@link MethodValidator} that makes sure that test methods not\n * annotated by the Test annotation works in JUnit 4.4 with the custom\n * JUnit-runner when the test class is extending {@link TestCase}. This is\n * actually a workaround for JUnit 4.4 when the test case extends from the\n * {@code TestCase} class.\n */\n@SuppressWarnings(\"deprecation\")\npublic class PowerMockJUnit4MethodValidator extends MethodValidator {\n\n    private static final String TEST_CLASS_FIELD;\n    private static final String CLASS_UNDER_TEST_FIELD;\n    private static final String ERRORS_FIELD;\n\n    static {\n        if(JUnitVersion.isGreaterThanOrEqualTo(\"4.12\")) {\n            TEST_CLASS_FIELD = \"testClass\";\n            CLASS_UNDER_TEST_FIELD = \"klass\";\n            ERRORS_FIELD = \"errors\";\n        }\n        else {\n            TEST_CLASS_FIELD = \"fTestClass\";\n            CLASS_UNDER_TEST_FIELD = \"fClass\";\n            ERRORS_FIELD = \"fErrors\";\n        }\n    }\n\n    public PowerMockJUnit4MethodValidator(TestClass testClass) {\n        super(testClass);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    public void validateInstanceMethods() {\n        validateTestMethods(After.class, false);\n        validateTestMethods(Before.class, false);\n        validateTestMethods(Test.class, false);\n\n        TestClass testClass = Whitebox.getInternalState(this, TEST_CLASS_FIELD, MethodValidator.class);\n        Class<?> classUnderTest = Whitebox.getInternalState(testClass, CLASS_UNDER_TEST_FIELD);\n        List<Throwable> fErrors = Whitebox.getInternalState(this, ERRORS_FIELD, MethodValidator.class);\n\n        List<Method> methods = getTestMethods(testClass, classUnderTest);\n        if (methods.size() == 0)\n            fErrors.add(new Exception(\"No runnable methods\"));\n    }\n\n    private List<Method> getTestMethods(TestClass testClass, Class<?> classUnderTest) {\n        List<Method> methods = testClass.getAnnotatedMethods(Test.class);\n        if (methods.isEmpty()) {\n            methods.addAll(getTestMethodsWithNoAnnotation(classUnderTest));\n        }\n        return methods;\n    }\n\n    /**\n     * This is a rip-off of the\n     * {@link MethodValidator#validateInstanceMethods()} with the exception that\n     * this method also searches for test methods if the class extends\n     * {@link TestCase} and has methods that starts with test which are not\n     * annotated.\n     */\n    @SuppressWarnings(\"unchecked\")\n    private void validateTestMethods(Class<? extends Annotation> annotation, boolean isStatic) {\n        TestClass testClass = Whitebox.getInternalState(this, TEST_CLASS_FIELD, MethodValidator.class);\n        Class<?> classUnderTest = Whitebox.getInternalState(testClass, CLASS_UNDER_TEST_FIELD);\n        final List<Method> methods;\n        if (TestCase.class.equals(classUnderTest.getSuperclass()) && !isStatic) {\n            methods = getTestMethodsWithNoAnnotation(classUnderTest);\n        } else {\n            methods = testClass.getAnnotatedMethods(annotation);\n        }\n\n        List<Throwable> fErrors = Whitebox.getInternalState(this, ERRORS_FIELD, MethodValidator.class);\n        for (Method each : methods) {\n            if (Modifier.isStatic(each.getModifiers()) != isStatic) {\n                String state = isStatic ? \"should\" : \"should not\";\n                fErrors.add(new Exception(\"Method \" + each.getName() + \"() \" + state + \" be static\"));\n            }\n            if (!Modifier.isPublic(each.getDeclaringClass().getModifiers()))\n                fErrors.add(new Exception(\"Class \" + each.getDeclaringClass().getName() + \" should be public\"));\n            if (!Modifier.isPublic(each.getModifiers()))\n                fErrors.add(new Exception(\"Method \" + each.getName() + \" should be public\"));\n            if (each.getReturnType() != Void.TYPE)\n                fErrors.add(new Exception(\"Method \" + each.getName() + \" should be void\"));\n            if (each.getParameterTypes().length != 0)\n                fErrors.add(new Exception(\"Method \" + each.getName() + \" should have no parameters\"));\n        }\n    }\n\n    private List<Method> getTestMethodsWithNoAnnotation(Class<?> testClass) {\n        List<Method> potentialTestMethods = new LinkedList<Method>();\n        Method[] methods = testClass.getMethods();\n        for (Method method : methods) {\n            if (method.getName().startsWith(\"test\")) {\n                potentialTestMethods.add(method);\n            }\n        }\n        return potentialTestMethods;\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4/src/test/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifierTest.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.internal.impl;\n\nimport org.junit.Test;\nimport org.junit.runner.Description;\nimport org.junit.runner.Result;\nimport org.junit.runner.RunWith;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunListener;\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runners.Parameterized;\nimport org.easymock.EasyMock;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\n@RunWith(Parameterized.class)\npublic class PowerMockRunNotifierTest {\n\n    /*\n     * Dummy test data ...\n     */\n    private static final Object[][] testDataAlternatives;\n    static {\n        Description description =\n                Description.createSuiteDescription(Description.class);\n        testDataAlternatives = new Object[][] {\n            {description},\n            {new Failure(description, new Throwable())},\n            {new RunListener()},\n            {new Result()}\n        };\n    }\n\n    /**\n     * Parameter data\n     */\n    @Parameterized.Parameter(0) public Method method;\n\n    @Parameterized.Parameters(name = \"{0}\")\n    public static List<?> runNotifierMethods() {\n        List<Object[]> methods = new ArrayList<Object[]>();\n        for (Method m : RunNotifier.class.getMethods()) {\n            if (Object.class != m.getDeclaringClass()) {\n                methods.add(new Object[] {m});\n            }\n        }\n        return methods;\n    }\n\n    @Test\n    public void verifyBackendRunNotifierIsProperlyNotified() throws Exception {\n        Object[] testData = retrieveSuitableTestData();\n        RunNotifier backendRunNotifierMock = createMock(RunNotifier.class);\n        method.invoke(backendRunNotifierMock, testData);\n        replay(backendRunNotifierMock);\n        method.invoke(new PowerMockRunNotifier(\n                backendRunNotifierMock,\n                EasyMock.<PowerMockTestNotifier, PowerMockTestNotifier>createNiceMock(PowerMockTestNotifier.class),\n                new Method[0]),\n                testData);\n        verify(backendRunNotifierMock);\n    }\n\n    private Object[] retrieveSuitableTestData() {\n        Class<?>[] paramTypes = method.getParameterTypes();\n        if (0 == paramTypes.length) {\n            return null;\n        }\n        for (Object[] testData : testDataAlternatives) {\n            if (paramTypes[0] == testData[0].getClass()) {\n                return testData;\n            }\n        }\n        throw new Error(\"No test-data available for method \" + method);\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/JUnit4TestSuiteChunker.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.manipulation.Filterable;\nimport org.junit.runner.manipulation.Sortable;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.tests.utils.RunnerTestSuiteChunker;\n\npublic interface JUnit4TestSuiteChunker extends RunnerTestSuiteChunker, Filterable, Sortable {\n\n\tDescription getDescription();\n\n\tvoid run(RunNotifier notifier);\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/PowerMockJUnitRunnerDelegate.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.RunNotifier;\n\npublic interface PowerMockJUnitRunnerDelegate {\n\n\tvoid run(final RunNotifier notifier);\n\n\tDescription getDescription();\n\n\tint getTestCount();\n\n\tClass<?> getTestClass();\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/AbstractCommonPowerMockRunner.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal.impl;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Runner;\nimport org.junit.runner.manipulation.Filter;\nimport org.junit.runner.manipulation.Filterable;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runner.manipulation.Sortable;\nimport org.junit.runner.manipulation.Sorter;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.core.MockRepository;\nimport org.powermock.modules.junit4.common.internal.JUnit4TestSuiteChunker;\nimport org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate;\n\npublic abstract class AbstractCommonPowerMockRunner extends Runner implements Filterable, Sortable {\n\n    private JUnit4TestSuiteChunker suiteChunker;\n\n    public AbstractCommonPowerMockRunner(Class<?> klass,\n                                         Class<? extends PowerMockJUnitRunnerDelegate> runnerDelegateImplClass) throws Exception {\n        suiteChunker = new JUnit4TestSuiteChunkerImpl(klass, runnerDelegateImplClass);\n        /*\n           * For extra safety clear the MockitoRepository on each new\n           * instantiation of the runner. This is good in cases where a previous\n           * test has used e.g. PowerMock#createMock(..) to create a mock without\n           * using this runner. That means that there's some state left in the\n           * MockRepository that hasn't been cleared. Currently clearing the\n           * MockRepository from any classloader will clear the previous state but\n           * it's not certain that this is always the case.\n           */\n        MockRepository.clear();\n    }\n\n    @Override\n    public Description getDescription() {\n        return suiteChunker.getDescription();\n    }\n\n    @Override\n    public void run(RunNotifier notifier) {\n        try {\n            suiteChunker.run(notifier);\n        } finally {\n            // To avoid out of memory errors!\n            suiteChunker = null;\n        }\n    }\n\n    @Override\n    public synchronized int testCount() {\n        return suiteChunker.getTestCount();\n    }\n\n    @Override\n    public void filter(Filter filter) throws NoTestsRemainException {\n        suiteChunker.filter(filter);\n    }\n\n    @Override\n    public void sort(Sorter sorter) {\n        suiteChunker.sort(sorter);\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestMethodChecker.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.modules.junit4.common.internal.impl;\n\nimport junit.framework.TestCase;\nimport org.junit.Test;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\n/**\n *\n */\npublic class JUnit4TestMethodChecker {\n    private final Class<?> testClass;\n    private final Method potentialTestMethod;\n\n    public JUnit4TestMethodChecker(Class<?> testClass, Method potentialTestMethod) {\n        this.testClass = testClass;\n        this.potentialTestMethod = potentialTestMethod;\n    }\n\n    public boolean isTestMethod() {\n        return isJUnit3TestMethod() || isJUnit4TestMethod();\n    }\n\n    protected boolean isJUnit4TestMethod() {return potentialTestMethod.isAnnotationPresent(Test.class);}\n\n    protected boolean isJUnit3TestMethod() {\n        return potentialTestMethod.getName().startsWith(\"test\")\n                       && Modifier.isPublic(potentialTestMethod.getModifiers())\n                       && potentialTestMethod.getReturnType()\n                                             .equals(Void.TYPE) && TestCase.class.isAssignableFrom(testClass);\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestSuiteChunkerImpl.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal.impl;\n\nimport org.junit.Test;\nimport org.junit.runner.Description;\nimport org.junit.runner.manipulation.Filter;\nimport org.junit.runner.manipulation.Filterable;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runner.manipulation.Sortable;\nimport org.junit.runner.manipulation.Sorter;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.core.spi.testresult.TestSuiteResult;\nimport org.powermock.core.spi.testresult.impl.TestSuiteResultImpl;\nimport org.powermock.modules.junit4.common.internal.JUnit4TestSuiteChunker;\nimport org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\nimport org.powermock.tests.utils.TestChunk;\nimport org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl;\nimport org.powermock.tests.utils.impl.PowerMockTestNotifierImpl;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class JUnit4TestSuiteChunkerImpl extends AbstractTestSuiteChunkerImpl<PowerMockJUnitRunnerDelegate> implements\n\t\tJUnit4TestSuiteChunker, Filterable, Sortable {\n\t\n    private static final Class<? extends Annotation> testMethodAnnotation = Test.class;\n\n\tprivate Description description;\n\tprivate final Class<? extends PowerMockJUnitRunnerDelegate> runnerDelegateImplementationType;\n\n\n\tJUnit4TestSuiteChunkerImpl(Class<?> testClass, Class<? extends PowerMockJUnitRunnerDelegate> runnerDelegateImplementationType) throws Exception {\n\t\tsuper(testClass);\n\t\tif (testClass == null) {\n\t\t\tthrow new IllegalArgumentException(\"You must supply a test class\");\n\t\t}\n\n\t\tif (runnerDelegateImplementationType == null) {\n\t\t\tthrow new IllegalArgumentException(\"Runner delegate type cannot be null.\");\n\t\t}\n\n\t\tthis.runnerDelegateImplementationType = runnerDelegateImplementationType;\n\n\t\ttry {\n\t\t\tcreateTestDelegators(testClass, getTestChunksEntries(testClass));\n\t\t} catch (InvocationTargetException e) {\n\t\t\tfinal Throwable cause = e.getCause();\n\t\t\tif (cause instanceof Exception) {\n\t\t\t\tthrow (Exception) cause;\n\t\t\t} else if (cause instanceof Error) {\n\t\t\t\tthrow (Error) cause;\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(cause);\n\t\t\t}\n\t\t}\n\n\t}\n\n    @Override\n\tpublic void run(RunNotifier notifier) {\n\t\tList<TestChunk> chunkEntries = getTestChunks();\n\t\tIterator<TestChunk> iterator = chunkEntries.iterator();\n\n\t\tif (delegates.size() != getChunkSize()) {\n\t\t\tthrow new IllegalStateException(\"Internal error: There must be an equal number of suites and delegates.\");\n\t\t}\n\n\t\tfinal Class<?> testClass = getTestClasses()[0];\n\t\tfinal PowerMockTestListener[] powerMockTestListeners = (PowerMockTestListener[]) getPowerMockTestListenersLoadedByASpecificClassLoader(\n\t\t\t\ttestClass, this.getClass().getClassLoader());\n\n\t    final Set<Method> allMethods = new LinkedHashSet<Method>();\n\t\tfor (TestChunk testChunk : getTestChunks()) {\n\t\t\tallMethods.addAll(testChunk.getTestMethodsToBeExecutedByThisClassloader());\n\t\t}\n\n\t\tfinal Method[] allMethodsAsArray = allMethods.toArray(new Method[allMethods.size()]);\n\t\tfinal PowerMockTestNotifier powerMockTestNotifier = new PowerMockTestNotifierImpl(powerMockTestListeners);\n\t\tpowerMockTestNotifier.notifyBeforeTestSuiteStarted(testClass, allMethodsAsArray);\n\n\t\tint failureCount = 0;\n\t\tint successCount = 0;\n\t\tint ignoreCount = 0;\n\n\t\tfor (PowerMockJUnitRunnerDelegate delegate : delegates) {\n\t\t\tTestChunk next = iterator.next();\n\t\t\tfinal ClassLoader key = next.getClassLoader();\n\t\t\tPowerMockJUnit4RunListener powerMockListener = new PowerMockJUnit4RunListener(key, powerMockTestNotifier);\n\t\t\tnotifier.addListener(powerMockListener);\n\t\t\tfinal ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();\n\t\t\tThread.currentThread().setContextClassLoader(key);\n\t\t\ttry {\n\t\t\t\tdelegate.run(notifier);\n\t\t\t} finally {\n\t\t\t\tThread.currentThread().setContextClassLoader(originalClassLoader);\n\t\t\t}\n\t\t\tfinal int failureCountForThisPowerMockListener = powerMockListener.getFailureCount();\n\t\t\tfinal int ignoreCountForThisPowerMockListener = powerMockListener.getIgnoreCount();\n\t\t\tfailureCount += failureCountForThisPowerMockListener;\n\t\t\tignoreCount += ignoreCountForThisPowerMockListener;\n\t\t\tsuccessCount += delegate.getTestCount() - failureCountForThisPowerMockListener\n\t\t\t\t\t- ignoreCountForThisPowerMockListener;\n\t\t\tnotifier.removeListener(powerMockListener);\n\t\t}\n\n\t\tfinal TestSuiteResult testSuiteResult = new TestSuiteResultImpl(failureCount, successCount, getTestCount(),\n\t\t\t\tignoreCount);\n\t\tpowerMockTestNotifier.notifyAfterTestSuiteEnded(testClass, allMethodsAsArray, testSuiteResult);\n\t}\n\n    @Override\n\tpublic boolean shouldExecuteTestForMethod(Class<?> testClass, Method potentialTestMethod) {\n\t\treturn new JUnit4TestMethodChecker(testClass, potentialTestMethod).isTestMethod();\n\t}\n\n\t@Override\n\tprotected Class<? extends Annotation> testMethodAnnotation() {\n\t\treturn testMethodAnnotation;\n\t}\n\n\t@Override\n\tprotected PowerMockJUnitRunnerDelegate createDelegatorFromClassloader(ClassLoader classLoader, Class<?> testClass,\n\t\t\tfinal List<Method> methodsToTest) throws Exception {\n\n\t\tSet<String> methodNames = new HashSet<String>();\n\t\tfor (Method method : methodsToTest) {\n\t\t\tmethodNames.add(method.getName());\n\t\t}\n\n\t\tfinal Class<?> testClassLoadedByMockedClassLoader = Class.forName(testClass.getName(), false, classLoader);\n\n\t\t/*\n\t\t * Array classes cannot be loaded be classloader.loadClass(..) in JDK 6.\n\t\t * See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6500212.\n\t\t */\n\t\tfinal Class<?> powerMockTestListenerArrayType = Class.forName(PowerMockTestListener[].class.getName(), false,\n\t\t\t\tclassLoader);\n\t\tfinal Class<?> delegateClass = Class.forName(runnerDelegateImplementationType.getName(), false, classLoader);\n\t\tConstructor<?> con = delegateClass.getConstructor(Class.class, String[].class,\n\t\t\t\tpowerMockTestListenerArrayType);\n        return (PowerMockJUnitRunnerDelegate) con.newInstance(\n                testClassLoadedByMockedClassLoader, methodNames.toArray(new String[methodNames.size()]),\n                getPowerMockTestListenersLoadedByASpecificClassLoader(testClass, classLoader));\n\t}\n\n\t@Override\n\tpublic synchronized int getTestCount() {\n\t\tif (testCount == NOT_INITIALIZED) {\n\t\t\ttestCount = 0;\n\t\t\tfor (PowerMockJUnitRunnerDelegate delegate : delegates) {\n\t\t\t\ttestCount += delegate.getTestCount();\n\t\t\t}\n\t\t}\n\t\treturn testCount;\n\t}\n\n\t@Override\n\tpublic Description getDescription() {\n\t\tif (description == null) {\n\t\t\tif (delegates.size() == 0) {\n\t\t\t\t/*\n\t\t\t\t * This happens if Test A extends Test B and B uses the @RunWith\n\t\t\t\t * annotation and there are no tests defined in class B.\n\t\t\t\t */\n\t\t\t\treturn Description.createTestDescription(this.getClass(), \"no tests in this class\");\n\t\t\t}\n\n\t\t\t// Use the first delegator as the base for the description.\n\t\t\tPowerMockJUnitRunnerDelegate delegate = delegates.get(0);\n\t\t\tdescription = delegate.getDescription();\n\n\t\t\t/*\n\t\t\t * Add the remaining descriptions of all the chunked delegators. We\n\t\t\t * do this to make sure that we avoid adding chunks as \"Unrooted\n\t\t\t * tests\".\n\t\t\t */\n\t\t\tfor (int i = 1; i < delegates.size(); i++) {\n\t\t\t\t// Get the method-level descriptions\n\t\t\t\tArrayList<Description> children = delegates.get(i).getDescription().getChildren();\n\t\t\t\t// Add all method-level descriptions to the main description.\n\t\t\t\tfor (Description methodDescription : children) {\n\t\t\t\t\tdescription.addChild(methodDescription);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn description;\n\t}\n\n\t@Override\n\tpublic void filter(Filter filter) throws NoTestsRemainException {\n\t\tfor (Object delegate : delegates) {\n\t\t\tif (delegate instanceof Filterable) {\n\t\t\t\t((Filterable) delegate).filter(filter);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void sort(Sorter sorter) {\n\t\tfor (Object delegate : delegates) {\n\t\t\tif (delegate instanceof Sortable) {\n\t\t\t\t((Sortable) delegate).sort(sorter);\n\t\t\t}\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnitVersion.java",
    "content": "/*\n * Copyright 2012 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal.impl;\n\nimport junit.runner.Version;\n\npublic class JUnitVersion {\n\n    public static boolean isGreaterThanOrEqualTo(String version) {\n        final String currentVersion = getJUnitVersion();\n        return new VersionComparator().compare(currentVersion, version) >= 0;\n    }\n\n    public static String getJUnitVersion() {\n        return Version.id();\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/PowerMockJUnit4RunListener.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal.impl;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunListener;\nimport org.powermock.core.MockRepository;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\n\npublic class PowerMockJUnit4RunListener extends RunListener {\n\n\tprivate final ClassLoader mockClassLoader;\n\n\tprivate int failureCount;\n\n\tprivate int ignoreCount;\n\n\tprivate boolean currentTestSuccessful = true;\n\n\tprivate final PowerMockTestNotifier powerMockTestNotifier;\n\n\tpublic PowerMockJUnit4RunListener(ClassLoader mockClassLoader, PowerMockTestNotifier powerMockTestNotifier) {\n\t\tthis.mockClassLoader = mockClassLoader;\n\t\tthis.powerMockTestNotifier = powerMockTestNotifier;\n\t}\n\n\t/**\n\t * Performs clean up after each test. The {@link MockRepository#clear()}\n\t * methods has to be called by the correct class loader for the state to be\n\t * cleared. Therefore it is invoked using reflection when the class is\n\t * loaded from the correct class loader.\n\t */\n\t@Override\n\tpublic void testFinished(Description description1) throws Exception {\n\t\tClass<?> mockRepositoryClass = mockClassLoader.loadClass(MockRepository.class.getName());\n\t\ttry {\n\t\t\tnotifyListenersOfTestResult();\n\t\t} finally {\n\t\t\t// Clear state\n\t\t\tWhitebox.invokeMethod(mockRepositoryClass, \"clear\");\n\t\t}\n\t}\n\n\t/**\n\t * @return The number of failed tests.\n\t */\n\tpublic int getFailureCount() {\n\t\treturn failureCount;\n\t}\n\n\t/**\n\t * @return The number of successful tests.\n\t */\n\tpublic int getIgnoreCount() {\n\t\treturn ignoreCount;\n\t}\n\n\t@Override\n\tpublic void testFailure(Failure failure) throws Exception {\n\t\tcurrentTestSuccessful = false;\n\t\tfailureCount++;\n\t}\n\n\t@Override\n\tpublic void testIgnored(Description description) throws Exception {\n\t\tignoreCount++;\n\t}\n\n\tprivate void notifyListenersOfTestResult() {\n\t\ttry {\n\t\t\tpowerMockTestNotifier.notifyAfterTestMethod(currentTestSuccessful);\n\t\t} finally {\n\t\t\tcurrentTestSuccessful = true;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/VersionComparator.java",
    "content": "/*\n * Copyright 2012 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal.impl;\n\nimport java.util.Comparator;\n\n/**\n * This code is copied from http://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java\n */\nclass VersionComparator implements Comparator {\n\n    public boolean equals(Object o1, Object o2) {\n        return compare(o1, o2) == 0;\n    }\n\n    @Override\n    public int compare(Object o1, Object o2) {\n        String version1 = (String) o1;\n        String version2 = (String) o2;\n\n        VersionTokenizer tokenizer1 = new VersionTokenizer(version1);\n        VersionTokenizer tokenizer2 = new VersionTokenizer(version2);\n\n        int number1 = 0, number2 = 0;\n        String suffix1 = \"\", suffix2 = \"\";\n\n        while (tokenizer1.MoveNext()) {\n            if (!tokenizer2.MoveNext()) {\n                do {\n                    number1 = tokenizer1.getNumber();\n                    suffix1 = tokenizer1.getSuffix();\n                    if (number1 != 0 || suffix1.length() != 0) {\n                        // Version one is longer than number two, and non-zero\n                        return 1;\n                    }\n                }\n                while (tokenizer1.MoveNext());\n\n                // Version one is longer than version two, but zero\n                return 0;\n            }\n\n            number1 = tokenizer1.getNumber();\n            suffix1 = tokenizer1.getSuffix();\n            number2 = tokenizer2.getNumber();\n            suffix2 = tokenizer2.getSuffix();\n\n            if (number1 < number2) {\n                // Number one is less than number two\n                return -1;\n            }\n            if (number1 > number2) {\n                // Number one is greater than number two\n                return 1;\n            }\n\n            boolean empty1 = suffix1.length() == 0;\n            boolean empty2 = suffix2.length() == 0;\n\n            if (empty1 && empty2) continue; // No suffixes\n            if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)\n            if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)\n\n            // Lexical comparison of suffixes\n            int result = suffix1.compareTo(suffix2);\n            if (result != 0) return result;\n\n        }\n        if (tokenizer2.MoveNext()) {\n            do {\n                number2 = tokenizer2.getNumber();\n                suffix2 = tokenizer2.getSuffix();\n                if (number2 != 0 || suffix2.length() != 0) {\n                    // Version one is longer than version two, and non-zero\n                    return -1;\n                }\n            }\n            while (tokenizer2.MoveNext());\n\n            // Version two is longer than version one, but zero\n            return 0;\n        }\n        return 0;\n    }\n}"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/VersionTokenizer.java",
    "content": "/*\n * Copyright 2012 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.common.internal.impl;\n\n/**\n * This code is copied from http://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java\n */\nclass VersionTokenizer {\n    private final String _versionString;\n    private final int _length;\n\n    private int _position;\n    private int _number;\n    private String _suffix;\n\n    public int getNumber() {\n        return _number;\n    }\n\n    public String getSuffix() {\n        return _suffix;\n    }\n\n    public VersionTokenizer(String versionString) {\n        if (versionString == null)\n            throw new IllegalArgumentException(\"versionString is null\");\n\n        _versionString = versionString;\n        _length = versionString.length();\n    }\n\n    public boolean MoveNext() {\n        _number = 0;\n        _suffix = \"\";\n\n        // No more characters\n        if (_position >= _length)\n            return false;\n\n        while (_position < _length) {\n            char c = _versionString.charAt(_position);\n            if (c < '0' || c > '9') break;\n            _number = _number * 10 + (c - '0');\n            _position++;\n        }\n\n        int suffixStart = _position;\n\n        while (_position < _length) {\n            char c = _versionString.charAt(_position);\n            if (c == '.') break;\n            _position++;\n        }\n\n        _suffix = _versionString.substring(suffixStart, _position);\n\n        if (_position < _length) _position++;\n\n        return true;\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-common/src/test/java/org/powermock/modules/junit4/common/internal/impl/JUnitVersionTest.java",
    "content": "package org.powermock.modules.junit4.common.internal.impl;\n\nimport org.junit.Test;\n\nimport static org.hamcrest.core.Is.is;\nimport static org.junit.Assert.assertThat;\n\npublic class JUnitVersionTest {\n\n    @Test public void\n    parses_version_numbers_with_chars() {\n        assertThat(JUnitVersion.isGreaterThanOrEqualTo(\"4.90b2\"), is(false));\n    }\n\n    @Test public void\n    parses_version_numbers_with_dash_snapshot() {\n        assertThat(JUnitVersion.isGreaterThanOrEqualTo(\"4.19-SNAPSHOT\"), is(false));\n    }\n\n    @Test public void\n    parses_version_numbers_with_dash_snapshot_where_version_is_before_current() {\n        assertThat(JUnitVersion.isGreaterThanOrEqualTo(\"4.1-SNAPSHOT\"), is(true));\n    }\n\n    @Test public void\n    parses_version_numbers_major_and_minor_versions() {\n        assertThat(JUnitVersion.isGreaterThanOrEqualTo(\"4.1.5\"), is(true));\n    }\n\n    @Test public void\n    parses_version_numbers_major_and_several_minor_versions() {\n        assertThat(JUnitVersion.isGreaterThanOrEqualTo(\"4.44.5.6\"), is(false));\n    }\n\n    @Test public void\n    parses_4_11_beta_1() {\n        assertThat(JUnitVersion.isGreaterThanOrEqualTo(\"4.111-beta-1\"), is(false));\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/PowerMockRunner.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.legacy;\n\nimport org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner;\nimport org.powermock.modules.junit4.legacy.internal.impl.PowerMockJUnit4LegacyRunnerDelegateImpl;\n\npublic class PowerMockRunner extends AbstractCommonPowerMockRunner {\n\n\tpublic PowerMockRunner(Class<?> klass) throws Exception {\n\t\tsuper(klass, PowerMockJUnit4LegacyRunnerDelegateImpl.class);\n\t}\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/PowerMockJUnit4LegacyFilter.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.legacy.internal.impl;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.manipulation.Filter;\n\n/**\n * A JUnit filter that will filter the methods specified in String[] passed to\n * the constructor (i.e. these are the only tests that will be run for a\n * particular test class).\n * \n * @author Johan Haleby\n */\npublic class PowerMockJUnit4LegacyFilter extends Filter {\n\n\tprivate final String[] methodNamesToRun;\n\n\tpublic PowerMockJUnit4LegacyFilter(String[] methodNamesToRun) {\n\t\tthis.methodNamesToRun = methodNamesToRun;\n\t}\n\n\t@Override\n\tpublic String describe() {\n\t\treturn methodNamesToRun.length + \" tests.\";\n\t}\n\n\t@Override\n\tpublic boolean shouldRun(Description description) {\n\t\tboolean shouldRun = false;\n\t\tfor (String testMethodName : methodNamesToRun) {\n\t\t\tif (testMethodName.equals(extractMethodName(description))) {\n\t\t\t\tshouldRun = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn shouldRun;\n\t}\n\n\tprivate String extractMethodName(Description description) {\n\t\tfinal String displayName = description.getDisplayName();\n\t\t/*\n\t\t * The test method name is the string to the left of the first\n\t\t * parenthesis.\n\t\t * testSayPrivateStatic(org.powermock.modules.junit4.legacy.singleton.StupidSingletonTest)\n\t\t * is an example of a display name.\n\t\t */\n\t\tfinal int indexOfParenthesis = displayName.indexOf('(');\n\t\tif (indexOfParenthesis == -1) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Internal error: Failed to find the test method name.\");\n\t\t}\n\t\treturn displayName.substring(0, indexOfParenthesis);\n\t}\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/PowerMockJUnit4LegacyRunnerDelegateImpl.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.legacy.internal.impl;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.internal.runners.BeforeAndAfterRunner;\nimport org.junit.internal.runners.InitializationError;\nimport org.junit.internal.runners.TestClassRunner;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate;\nimport org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround.PowerMockJUnit4LegacyTestClassMethodsRunner;\nimport org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround.PowerMockJUnit4LegacyTestIntrospector;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.impl.MockPolicyInitializerImpl;\n\n/**\n * A JUnit4 legacy (i.e. v4.0-4.3) test runner that only runs a specified set of\n * test methods in a test class.\n * \n * <p>\n * Most parts of this class is essentially a rip off from\n * {@link TestClassRunner} used in JUnit 4.3.\n * \n * @see TestClassRunner\n * \n */\npublic class PowerMockJUnit4LegacyRunnerDelegateImpl extends TestClassRunner implements PowerMockJUnitRunnerDelegate {\n\n\tprivate final int testCount;\n\n\tpublic PowerMockJUnit4LegacyRunnerDelegateImpl(Class<?> klass, String[] methodsToRun,\n\t\t\tPowerMockTestListener[] listeners) throws InitializationError, NoTestsRemainException {\n\t\tsuper(klass, new PowerMockJUnit4LegacyTestClassMethodsRunner(klass,\n\t\t\t\tlisteners == null ? new PowerMockTestListener[0] : listeners));\n\t\tfilter(new PowerMockJUnit4LegacyFilter(methodsToRun));\n\n\t\ttestCount = methodsToRun.length;\n\t}\n\n\tpublic PowerMockJUnit4LegacyRunnerDelegateImpl(Class<?> klass, String[] methodsToRun) throws InitializationError,\n\t\t\tNoTestsRemainException {\n\t\tthis(klass, methodsToRun, null);\n\t}\n\n\t@Override\n\tpublic void run(final RunNotifier notifier) {\n\t\tBeforeAndAfterRunner runner = new BeforeAndAfterRunner(getTestClass(), BeforeClass.class, AfterClass.class,\n\t\t\t\tnull) {\n\n\t\t\t@Override\n\t\t\tprotected void runUnprotected() {\n\t\t\t\tfEnclosedRunner.run(notifier);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void addFailure(Throwable targetException) {\n\t\t\t\tnotifier.fireTestFailure(new Failure(getDescription(), targetException));\n\t\t\t}\n\t\t};\n\n\t\tWhitebox.setInternalState(runner, \"fTestIntrospector\",\n\t\t\t\tnew PowerMockJUnit4LegacyTestIntrospector(getTestClass()), BeforeAndAfterRunner.class);\n\n\t\t// Initialize mock policies for each test\n\t\tfinal ClassLoader classLoader = this.getClass().getClassLoader();\n\t\tnew MockPolicyInitializerImpl(getTestClass()).initialize(classLoader);\n\t\tThread.currentThread().setContextClassLoader(classLoader);\n\t\trunner.runProtected();\n\t}\n\n\tpublic int getTestCount() {\n\t\treturn testCount;\n\t}\n\n\t@Override\n\tpublic Class<?> getTestClass() {\n\t\treturn super.getTestClass();\n\t}\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/testcaseworkaround/PowerMockJUnit4LegacyTestClassMethodsRunner.java",
    "content": "package org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround;\n\nimport junit.framework.TestCase;\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.internal.runners.TestClassMethodsRunner;\nimport org.junit.internal.runners.TestMethodRunner;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.core.spi.PowerMockTestListener;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\nimport org.powermock.tests.utils.impl.PowerMockTestNotifierImpl;\nimport org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * Since {@link TestClassMethodsRunner} creates a new instance of\n * TestInterceptor in its constructor we need to manually lookup the additional\n * methods that should be added when extending from {@code TestCase}.\n */\npublic class PowerMockJUnit4LegacyTestClassMethodsRunner extends TestClassMethodsRunner {\n\n\tprivate final PowerMockTestNotifier powerMockTestNotifier;\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic PowerMockJUnit4LegacyTestClassMethodsRunner(Class<?> klass, PowerMockTestListener[] powerMockTestListeners) {\n\t\tsuper(klass);\n\t\tthis.powerMockTestNotifier = new PowerMockTestNotifierImpl(powerMockTestListeners);\n\t\tList<Method> testMethods = Whitebox.getInternalState(this, \"fTestMethods\", TestClassMethodsRunner.class);\n\t\ttestMethods.addAll(getAdditionalTestMethods(klass));\n\t}\n\n\tprivate List<Method> getAdditionalTestMethods(Class<?> klass) {\n\t\tList<Method> additionalMethods = new LinkedList<Method>();\n\t\tif (klass != null && klass.getSuperclass().equals(TestCase.class)) {\n\t\t\t/*\n\t\t\t * We now know that we need to add additional test methods because\n\t\t\t * JUnit4 ignores public methods with no @Test annotation when\n\t\t\t * extending from TestCase.\n\t\t\t */\n\t\t\tMethod[] methods = klass.getMethods();\n\t\t\tfor (Method method : methods) {\n\t\t\t\tif (isAdditionalTestMethod(method)) {\n\t\t\t\t\tadditionalMethods.add(method);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn additionalMethods;\n\n\t}\n\n\tprivate boolean isAdditionalTestMethod(Method method) {\n\t\treturn !method.isAnnotationPresent(Ignore.class) && method.getName().startsWith(\"test\") && Modifier.isPublic(method.getModifiers())\n\t\t\t\t&& method.getReturnType().equals(Void.TYPE) && method.getAnnotation(Test.class) == null;\n\t}\n\n\t@Override\n\tprotected TestMethodRunner createMethodRunner(Object test, Method method, RunNotifier notifier) {\n\t\treturn new PowerMockJUnit4LegacyTestMethodRunner(test, method, notifier, methodDescription(method), powerMockTestNotifier);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic void run(RunNotifier notifier) {\n\t\tfinal List<Method> methods = Whitebox.getInternalState(this, \"fTestMethods\");\n\t\tif (methods.isEmpty())\n\t\t\tnotifier.testAborted(getDescription(), new Exception(\"No runnable methods\"));\n\t\tfor (Method method : methods) {\n\t\t\tfinal StaticConstructorSuppressExtractorImpl staticConstructorSuppressExtractorImpl = new StaticConstructorSuppressExtractorImpl();\n\t\t\tClass<?> testType = getTestClass();\n\t\t\tfinal ClassLoader thisClassLoader = getClass().getClassLoader();\n\t\t\tif (!thisClassLoader.equals(testType.getClassLoader())) {\n\t\t\t\t/*\n\t\t\t\t * The test is loaded from another classloader, this means that\n\t\t\t\t * we cannot get the correct annotations if we don't load the\n\t\t\t\t * class from the correct class loader\n\t\t\t\t */\n\t\t\t\ttry {\n\t\t\t\t\ttestType = thisClassLoader.loadClass(testType.getName());\n\t\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\t\t// This should never happen\n\t\t\t\t\tthrow new RuntimeException(\"Internal error in PowerMock\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (staticConstructorSuppressExtractorImpl.getTestClasses(method) == null) {\n\t\t\t\tstaticConstructorSuppressExtractorImpl.getTestClasses(testType);\n\t\t\t}\n\n\t\t\tinvokeTestMethod(method, notifier);\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/testcaseworkaround/PowerMockJUnit4LegacyTestIntrospector.java",
    "content": "package org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround;\n\nimport org.junit.Test;\nimport org.junit.Test.None;\nimport org.junit.internal.runners.TestIntrospector;\n\nimport java.lang.reflect.Method;\n\n/**\n * A custom {@link TestIntrospector} that supports methods not annotated by the\n * Test annotation but should still be executed in the test case. This is\n * actually a workaround for the JUnit 4 test runner when the test case extends\n * from the {@code TestCase} class.\n */\npublic class PowerMockJUnit4LegacyTestIntrospector extends TestIntrospector {\n\n\tprivate static final long NO_TIMEOUT = 0L;\n\n\tpublic PowerMockJUnit4LegacyTestIntrospector(Class<?> testClass) {\n\t\tsuper(testClass);\n\t}\n\n\t@SuppressWarnings(\"all\")\n\tpublic long getTimeout(Method method) {\n\t\tTest annotation = method.getAnnotation(Test.class);\n\t\tlong timeout = annotation == null ? NO_TIMEOUT : annotation.timeout();\n\t\treturn timeout;\n\t}\n\n\t@SuppressWarnings(\"all\")\n\tpublic Class<? extends Throwable> expectedException(Method method) {\n\t\tTest annotation = method.getAnnotation(Test.class);\n\t\tif (annotation == null || annotation.expected() == None.class)\n\t\t\treturn null;\n\t\telse\n\t\t\treturn annotation.expected();\n\t}\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/testcaseworkaround/PowerMockJUnit4LegacyTestMethodRunner.java",
    "content": "package org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround;\n\nimport junit.framework.TestCase;\nimport org.junit.internal.runners.BeforeAndAfterRunner;\nimport org.junit.internal.runners.TestIntrospector;\nimport org.junit.internal.runners.TestMethodRunner;\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.PowerMockTestNotifier;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\n/**\n * This class is needed because the test method runner creates a new instance of\n * a {@link TestIntrospector} in its constructor. The TestIntrospector needs to\n * be changed in order to support methods not annotated with Test to avoid\n * NPE's.\n * <p>\n * This class also executes the setUp and tearDown methods if the test case\n * extends TestCase. Another thing it does is to invoke all PowerMock test\n * listeners for events.\n */\npublic class PowerMockJUnit4LegacyTestMethodRunner extends TestMethodRunner {\n\n\tprivate final PowerMockJUnit4LegacyTestIntrospector testIntrospector;\n\n\tprivate final Method method;\n\tprivate final Description description;\n\tprivate final RunNotifier notifier;\n\n\tprivate final PowerMockTestNotifier powerMockTestNotifier;\n\n\tpublic PowerMockJUnit4LegacyTestMethodRunner(Object test, Method method, RunNotifier notifier,\n\t\t\tDescription description, PowerMockTestNotifier powerMockTestNotifier) {\n\t\tsuper(test, method, notifier, description);\n\t\tthis.method = method;\n\t\tthis.description = description;\n\t\tthis.notifier = notifier;\n\t\tthis.powerMockTestNotifier = powerMockTestNotifier;\n\t\ttestIntrospector = new PowerMockJUnit4LegacyTestIntrospector(test.getClass());\n\t\tWhitebox.setInternalState(this, \"fTestIntrospector\", testIntrospector, TestMethodRunner.class);\n\t\tWhitebox.setInternalState(this, \"fTestIntrospector\", testIntrospector, BeforeAndAfterRunner.class);\n\t}\n\n\t@Override\n\tpublic void run() {\n\t\tif (testIntrospector.isIgnored(method)) {\n\t\t\tnotifier.fireTestIgnored(description);\n\t\t\treturn;\n\t\t}\n\t\tnotifier.fireTestStarted(description);\n\t\ttry {\n\t\t\tpowerMockTestNotifier.notifyBeforeTestMethod(Whitebox.getInternalState(this, \"fTest\"), method,\n\t\t\t\t\tnew Object[0]);\n\t\t\tlong timeout = testIntrospector.getTimeout(method);\n\n\t\t\t// Execute the the setUp method if needed\n\t\t\texecuteMethodInTestInstance(\"setUp\");\n\t\t\tif (timeout > 0) {\n\t\t\t\t// The runWithTimeout method is private in the super class,\n\t\t\t\t// invoke it using reflection.\n\t\t\t\tWhitebox.invokeMethod(this, TestMethodRunner.class, \"runWithTimeout\", timeout);\n\t\t\t} else {\n\t\t\t\tWhitebox.invokeMethod(this, TestMethodRunner.class, \"runMethod\");\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\texecuteMethodInTestInstance(\"tearDown\");\n\t\t\t} finally {\n\t\t\t\tnotifier.fireTestFinished(description);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * This method takes care of executing a method in the test object <i>if</i>\n\t * this object extends from {@link TestCase}. It can be used to execute the\n\t * setUp and tearDown methods for example.\n\t */\n\tprivate void executeMethodInTestInstance(String methodName) {\n\t\tif (TestCase.class.isAssignableFrom(Whitebox.getInternalState(this, \"fTest\").getClass())) {\n\t\t\tObject object = Whitebox.getInternalState(this, \"fTest\");\n\t\t\ttry {\n\t\t\t\tif (object != null) {\n\t\t\t\t\tWhitebox.invokeMethod(object, methodName);\n\t\t\t\t}\n\t\t\t} catch (Throwable e) {\n\t\t\t\tif (e instanceof RuntimeException) {\n\t\t\t\t\tthrow (RuntimeException) e;\n\t\t\t\t}\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void runUnprotected() {\n\t\ttry {\n\t\t\texecuteMethodBody();\n\t\t\tif (expectsException())\n\t\t\t\taddFailure(new AssertionError(\"Expected exception: \" + expectedException().getName()));\n\t\t} catch (InvocationTargetException e) {\n\t\t\tThrowable actual = e.getTargetException();\n\t\t\tif (!expectsException())\n\t\t\t\taddFailure(actual);\n\t\t\telse if (isUnexpected(actual)) {\n\t\t\t\tString message = \"Unexpected exception, expected<\" + expectedException().getName() + \"> but was<\"\n\t\t\t\t\t\t+ actual.getClass().getName() + \">\";\n\t\t\t\taddFailure(new Exception(message, actual));\n\t\t\t}\n\t\t} catch (Throwable e) {\n\t\t\taddFailure(e);\n\t\t}\n\t}\n\n\tprivate boolean isUnexpected(Throwable exception) {\n\t\treturn !expectedException().isAssignableFrom(exception.getClass());\n\t}\n\n\tprivate boolean expectsException() {\n\t\treturn expectedException() != null;\n\t}\n\n\tprivate Class<? extends Throwable> expectedException() {\n\t\treturn testIntrospector.expectedException(method);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-rule/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.rule;\n\nimport org.junit.rules.MethodRule;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.api.support.SafeExceptionRethrower;\nimport org.powermock.classloading.ClassloaderExecutor;\nimport org.powermock.classloading.SingleClassloaderExecutor;\nimport org.powermock.classloading.spi.DoNotClone;\nimport org.powermock.core.MockRepository;\nimport org.powermock.tests.utils.MockPolicyInitializer;\nimport org.powermock.tests.utils.TestChunk;\nimport org.powermock.tests.utils.TestSuiteChunker;\nimport org.powermock.tests.utils.impl.MockPolicyInitializerImpl;\n\npublic class PowerMockRule implements MethodRule {\n\tprivate static Class<?> previousTargetClass;\n\tprivate static MockPolicyInitializer mockPolicyInitializer;\n\n    @DoNotClone\n\tprivate static TestSuiteChunker testSuiteChunker;\n\n\n\t@Override\n\tpublic Statement apply(final Statement base, final FrameworkMethod method, final Object target) {\n        if (isNotRuleInitialized(target)) {\n            init(target);\n\t\t}\n\t\treturn new PowerMockStatement(base, testSuiteChunker.getTestChunk(method.getMethod()), mockPolicyInitializer);\n\t}\n\n    protected boolean isNotRuleInitialized(Object target) {return testSuiteChunker  == null || previousTargetClass != target.getClass();}\n\n    protected void init(Object target) {\n        final Class<?> testClass = target.getClass();\n\n        try {\n            mockPolicyInitializer = new MockPolicyInitializerImpl(testClass);\n            testSuiteChunker = new PowerMockRuleTestSuiteChunker(testClass);\n            previousTargetClass = target.getClass();\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n}\n\nclass PowerMockStatement extends Statement {\n\tprivate final Statement fNext;\n    private final ClassloaderExecutor classloaderExecutor;\n\tprivate final MockPolicyInitializer mockPolicyInitializer;\n\n    public PowerMockStatement(Statement fNext, TestChunk testChunk, MockPolicyInitializer mockPolicyInitializer) {\n        this.fNext = fNext;\n        this.mockPolicyInitializer = mockPolicyInitializer;\n        this.classloaderExecutor = new SingleClassloaderExecutor(testChunk.getClassLoader());\n    }\n\n    @Override\n\tpublic void evaluate() throws Throwable {\n\t\tclassloaderExecutor.execute(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\t// Re-executes the policy method that might initialize mocks that \n\t\t\t\t\t// were cleared after the previous statement.\n\t\t\t\t\t// This fixes https://github.com/jayway/powermock/issues/581\n\t\t\t\t\tmockPolicyInitializer.refreshPolicies(getClass().getClassLoader());\n\t\t\t\t\tfNext.evaluate();\n\t\t\t\t} catch (Throwable e) {\n\t\t\t\t\tSafeExceptionRethrower.safeRethrow(e);\n\t\t\t\t} finally {\n\t\t\t\t\t// Clear the mock repository after each test\n\t\t\t\t\tMockRepository.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-rule/src/main/java/org/powermock/modules/junit4/rule/PowerMockRuleTestSuiteChunker.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.modules.junit4.rule;\n\nimport org.powermock.modules.junit4.common.internal.impl.JUnit4TestMethodChecker;\nimport org.powermock.tests.utils.impl.AbstractCommonTestSuiteChunkerImpl;\n\nimport java.lang.reflect.Method;\n\n/**\n *\n */\npublic class PowerMockRuleTestSuiteChunker extends AbstractCommonTestSuiteChunkerImpl {\n\n    public PowerMockRuleTestSuiteChunker(Class testClass) throws Exception {\n        super(testClass);\n    }\n\n    @Override\n    public boolean shouldExecuteTestForMethod(Class<?> testClass, Method potentialTestMethod) {\n        return new JUnit4TestMethodChecker(testClass, potentialTestMethod).isTestMethod();\n    }\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-junit4-rule-agent/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.junit4.rule;\n\nimport org.junit.rules.MethodRule;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.agent.JavaAgentClassRegister;\nimport org.powermock.core.agent.JavaAgentFrameworkRegister;\nimport org.powermock.core.agent.JavaAgentFrameworkRegisterFactory;\nimport org.powermock.modules.agent.PowerMockAgent;\nimport org.powermock.modules.agent.support.JavaAgentClassRegisterImpl;\nimport org.powermock.modules.agent.support.PowerMockAgentTestInitializer;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\npublic class PowerMockRule implements MethodRule {\n    static {\n        if (PowerMockRule.class.getClassLoader() != ClassLoader.getSystemClassLoader()) {\n            throw new IllegalStateException(\"PowerMockRule can only be used with the system classloader but was loaded by \" + PowerMockRule.class.getClassLoader());\n        }\n        PowerMockAgent.initializeIfPossible();\n    }\n\n    @Override\n    public Statement apply(Statement base, FrameworkMethod method, Object target) {\n\n        JavaAgentClassRegister agentClassRegister = new JavaAgentClassRegisterImpl();\n        PowerMockAgentTestInitializer.initialize(target.getClass(), agentClassRegister);\n\n        return new PowerMockStatement(base, target, agentClassRegister);\n    }\n}\n\nclass PowerMockStatement extends Statement {\n    private static final String ANNOTATION_ENABLER = \"org.powermock.api.extension.listener.AnnotationEnabler\";\n    private final Statement fNext;\n    private final Object target;\n    private final JavaAgentClassRegister agentClassRegister;\n    private final JavaAgentFrameworkRegister javaAgentFrameworkRegister;\n\n    public PowerMockStatement(Statement base, Object target, JavaAgentClassRegister agentClassRegister) {\n        this.fNext = base;\n        this.target = target;\n        this.agentClassRegister = agentClassRegister;\n        this.javaAgentFrameworkRegister = JavaAgentFrameworkRegisterFactory.create();\n    }\n\n    @Override\n    public void evaluate() throws Throwable {\n        Object annotationEnabler = loadAnnotationEnableIfPresent();\n        try {\n            injectMocksUsingAnnotationEnabler(target, annotationEnabler);\n            setFrameworkAgentClassRegister();\n            fNext.evaluate();\n        } finally {\n            // Clear the mock repository after each test\n            MockRepository.clear();\n            clearMockFields(target, annotationEnabler);\n            clearFrameworkAgentClassRegister();\n        }\n    }\n    \n    private void clearFrameworkAgentClassRegister() {\n        agentClassRegister.clear();\n        javaAgentFrameworkRegister.clear();\n    }\n    \n    private void setFrameworkAgentClassRegister() {\n        javaAgentFrameworkRegister.set(agentClassRegister);\n    }\n\n    private Object loadAnnotationEnableIfPresent() {\n        boolean hasAnnotationEnabler = hasAnnotationEnablerClass();\n        if (!hasAnnotationEnabler) {\n            return null;\n        }\n\n        try {\n            return Whitebox.invokeConstructor(Class.forName(ANNOTATION_ENABLER, true, Thread.currentThread().getContextClassLoader()));\n        } catch (Exception e) {\n            throw new RuntimeException(\"PowerMock internal error, failed to load annotation enabler.\");\n        }\n    }\n\n    private boolean hasAnnotationEnablerClass() {\n        try {\n            Class.forName(ANNOTATION_ENABLER, false, Thread.currentThread().getContextClassLoader());\n            return true;\n        } catch (ClassNotFoundException e) {\n            return false;\n        }\n    }\n\n    private void clearMockFields(Object target, Object annotationEnabler) throws Exception {\n        if (annotationEnabler != null) {\n            Class<? extends Annotation>[] mockAnnotations = Whitebox.invokeMethod(annotationEnabler, \"getMockAnnotations\");\n            Set<Field> mockFields = Whitebox.getFieldsAnnotatedWith(target, mockAnnotations);\n            for (Field field : mockFields) {\n                field.set(target, null);\n            }\n        }\n    }\n\n    private void injectMocksUsingAnnotationEnabler(Object target, Object annotationEnabler) throws Exception {\n        if (annotationEnabler != null) {\n            Whitebox.invokeMethod(annotationEnabler, \"beforeTestMethod\", new Class<?>[]{Object.class, Method.class,\n                    Object[].class}, target, null, null);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.testng.internal.PowerMockClassloaderObjectFactory;\nimport org.testng.IObjectFactory;\nimport org.testng.internal.ObjectFactoryImpl;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\n\n/**\n * The PowerMock object factory. If the test class or any public method declared in the test class is annotated with\n * {@link PrepareForTest} or {@link SuppressStaticInitializationFor} the PowerMock classloader will enable the class\n * for PowerMock testing, otherwise a standard ObjectFactory is used.\n */\npublic class PowerMockObjectFactory implements IObjectFactory {\n\n    private PowerMockClassloaderObjectFactory powerMockObjectFactory = new PowerMockClassloaderObjectFactory();\n\n    private ObjectFactoryImpl defaultObjectFactory = new ObjectFactoryImpl();\n\n    @Override\n    public Object newInstance(Constructor constructor, Object... params) {\n        final Object testInstance;\n        Class<?> testClass = constructor.getDeclaringClass();\n        if (hasPowerMockAnnotation(testClass)) {\n            testInstance = powerMockObjectFactory.newInstance(constructor, params);\n        }\n        else {\n            testInstance = defaultObjectFactory.newInstance(constructor, params);\n        }\n\n        return testInstance;\n    }\n\n    private boolean hasPowerMockAnnotation(Class<?> testClass) {\n        return isClassAnnotatedWithPowerMockAnnotation(testClass) || anyMethodInClassHasPowerMockAnnotation(testClass);\n    }\n\n    private boolean anyMethodInClassHasPowerMockAnnotation(Class<?> testClass) {\n        final Method[] methods = testClass.getMethods();\n        for (Method method : methods) {\n            if(method.isAnnotationPresent(PrepareForTest.class) || method.isAnnotationPresent(SuppressStaticInitializationFor.class)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    private boolean isClassAnnotatedWithPowerMockAnnotation(Class<?> testClass) {\n        return testClass.isAnnotationPresent(PrepareForTest.class) || testClass.isAnnotationPresent(SuppressStaticInitializationFor.class);\n    }\n}"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/Assumes.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.modules.testng.internal;\n\nimport org.testng.SkipException;\n\n/**\n *\n */\npublic class Assumes {\n\n    public static void assumeTrue(String reason, boolean assertion) {\n        if (!assertion) {\n            throw new SkipException(reason);\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockClassloaderObjectFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage org.powermock.modules.testng.internal;\n\nimport org.powermock.core.MockRepository;\nimport org.testng.IObjectFactory;\n\nimport java.lang.reflect.Constructor;\n\npublic class PowerMockClassloaderObjectFactory implements IObjectFactory {\n\n    private final TestNGMockClassLoaderFactory classLoaderFactory;\n\n    public PowerMockClassloaderObjectFactory() {\n        classLoaderFactory = new TestNGMockClassLoaderFactory();\n    }\n\n    @Override\n    public Object newInstance(Constructor constructor, Object... params) {\n\n        /*\n         * For extra safety clear the MockitoRepository on each new\n\t\t * instantiation of the object factory. This is good in cases where a\n\t\t * previous test has used e.g. PowerMock#createMock(..) to create a mock\n\t\t * without using this factory. That means that there's some state left in\n\t\t * the MockRepository that hasn't been cleared. Currently clearing the\n\t\t * MockRepository from any classloader will clear the previous state but\n\t\t * it's not certain that this is always the case.\n\t\t */\n        MockRepository.clear();\n\n        return new TestClassInstanceFactory(constructor, classLoaderFactory, params).create();\n    }\n\n\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockExpectedExceptionsExtractorImpl.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.testng.internal;\n\nimport org.powermock.tests.utils.IgnorePackagesExtractor;\nimport org.testng.annotations.Test;\n\nimport java.lang.reflect.AnnotatedElement;\nimport java.lang.reflect.Method;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class PowerMockExpectedExceptionsExtractorImpl implements IgnorePackagesExtractor {\n\n    public String[] getPackagesToIgnore(AnnotatedElement element) {\n        List<String> ignoredPackages = new LinkedList<String>();\n        if (element instanceof Class<?>) {\n            Class<?> klazz = (Class<?>) element;\n            for (Method method : klazz.getMethods()) {\n                Test annotation = method.getAnnotation(Test.class);\n                if (annotation != null) {\n                    Class<?>[] ignores = annotation.expectedExceptions();\n                    if (ignores != null) {\n                        for (Class<?> ignorePackage : ignores) {\n                            ignoredPackages.add(ignorePackage.getName());\n                        }\n                    }\n                }\n            }\n            Class<?> superclass = klazz.getSuperclass();\n            if (superclass != null && !superclass.equals(Object.class)) {\n                String[] packagesToIgnore = getPackagesToIgnore(superclass);\n                ignoredPackages.addAll(Arrays.asList(packagesToIgnore));\n            }\n        }\n\n        return ignoredPackages.toArray(new String[ignoredPackages.size()]);\n    }\n}\n\n"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockTestNGMethodHandler.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.testng.internal;\n\nimport javassist.util.proxy.MethodHandler;\nimport org.powermock.core.MockRepository;\nimport org.powermock.reflect.Whitebox;\nimport org.testng.annotations.Test;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\n/*\n * Javassist handler that takes care of cleaning up {@link MockRepository} state\n * after each method annotated with {@link Test}.\n */\npublic class PowerMockTestNGMethodHandler implements MethodHandler {\n\n    private Object annotationEnabler;\n\n    public PowerMockTestNGMethodHandler(Class<?> testClass) {\n        try {\n            Class<?> annotationEnablerClass = Class.forName(\"org.powermock.api.extension.listener.AnnotationEnabler\");\n            annotationEnabler = Whitebox.newInstance(annotationEnablerClass);\n        } catch (ClassNotFoundException e) {\n            annotationEnabler = null;\n        }\n    }\n\n    @Override\n    public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {\n        injectMocksUsingAnnotationEnabler(self);\n        try {\n            final Object result = proceed.invoke(self, args);\n            return result;\n        } catch (InvocationTargetException e) {\n            throw e.getTargetException();\n        }\n        finally\n        {\n            if (thisMethod.isAnnotationPresent(Test.class)) {\n                clearMockFields();\n                MockRepository.clear();\n            }\n        }\n    }\n\n    private void clearMockFields() throws Exception, IllegalAccessException {\n        if (annotationEnabler != null) {\n            Set<Field> mockFields = Whitebox.getFieldsAnnotatedWith(this, Whitebox\n                    .<Class<? extends Annotation>[]> invokeMethod(annotationEnabler, \"getMockAnnotations\"));\n            for (Field field : mockFields) {\n                field.set(this, null);\n            }\n        }\n    }\n\n    private void injectMocksUsingAnnotationEnabler(Object self) throws Exception {\n        if (annotationEnabler != null) {\n            Whitebox.invokeMethod(annotationEnabler, \"beforeTestMethod\", new Class<?>[] { Object.class, Method.class,\n                    Object[].class }, self, null, null);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestClassInstanceFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.modules.testng.internal;\n\nimport javassist.util.proxy.ProxyFactory;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.tests.utils.impl.MockPolicyInitializerImpl;\n\nimport java.lang.reflect.Constructor;\n\nclass TestClassInstanceFactory {\n    private final Constructor constructor;\n    private final Class<?> testClass;\n    private final Object[] params;\n    private final ClassLoader mockLoader;\n\n    TestClassInstanceFactory(Constructor constructor, TestNGMockClassLoaderFactory classLoaderFactory, Object... params) {\n        this.constructor = constructor;\n        this.params = params;\n        this.testClass = constructor.getDeclaringClass();\n        this.mockLoader = classLoaderFactory.createClassLoader(testClass);\n    }\n\n     Object create() {\n\n        try {\n\n            initializeMockPolicy();\n\n            final Class<?> testClassLoadedByMockedClassLoader = createTestClass(testClass);\n            final Constructor<?> con = testClassLoadedByMockedClassLoader.getConstructor(constructor.getParameterTypes());\n            final Object testInstance = con.newInstance(params);\n\n            if (!extendsPowerMockTestCase(testClass)) {\n                setInvocationHandler(testInstance);\n            }\n\n            return testInstance;\n        } catch (Exception e) {\n            throw new RuntimeException(String.format(\"Cannot create a new instance of test class %s\", testClass), e);\n        }\n    }\n\n    private void initializeMockPolicy() {new MockPolicyInitializerImpl(testClass).initialize(mockLoader);}\n\n\n    /**\n     * We proxy the test class in order to be able to clear state after each\n     * test method invocation. It would be much better to be able to register a\n     * testng listener programmtically but I cannot find a way to do so.\n     */\n    private Class<?> createTestClass(Class<?> actualTestClass) throws Exception {\n\n        final Class<?> testClassLoadedByMockedClassLoader = Class.forName(actualTestClass.getName(), false, mockLoader);\n\n        if (extendsPowerMockTestCase(actualTestClass)) {\n            return testClassLoadedByMockedClassLoader;\n        } else {\n            return createProxyTestClass(testClassLoadedByMockedClassLoader);\n        }\n    }\n\n    private Class<?> createProxyTestClass(Class<?> testClassLoadedByMockedClassLoader) throws Exception {\n        Class<?> proxyFactoryClass = Class.forName(ProxyFactory.class.getName(), false, mockLoader);\n        final Class<?> testNGMethodFilterByMockedClassLoader = Class.forName(TestNGMethodFilter.class.getName(), false, mockLoader);\n\n        Object f = proxyFactoryClass.newInstance();\n        Object filter = testNGMethodFilterByMockedClassLoader.newInstance();\n        Whitebox.invokeMethod(f, \"setFilter\", filter);\n        Whitebox.invokeMethod(f, \"setSuperclass\", testClassLoadedByMockedClassLoader);\n\n        return Whitebox.invokeMethod(f, \"createClass\");\n    }\n\n    private void setInvocationHandler(Object testInstance) throws Exception {\n        Class<?> powerMockTestNGMethodHandlerClass = Class.forName(PowerMockTestNGMethodHandler.class.getName(), false, mockLoader);\n        Object powerMockTestNGMethodHandlerInstance = powerMockTestNGMethodHandlerClass.getConstructor(Class.class)\n                                                                                       .newInstance(\n                                                                                               testInstance.getClass());\n        Whitebox.invokeMethod(testInstance, \"setHandler\", powerMockTestNGMethodHandlerInstance);\n    }\n\n    private boolean extendsPowerMockTestCase(Class<?> actualTestClass) {\n        return PowerMockTestCase.class.isAssignableFrom(actualTestClass);\n    }\n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMethodFilter.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.testng.internal;\n\nimport javassist.util.proxy.MethodFilter;\n\nimport java.lang.reflect.Method;\n\n/**\n * Javassist method filter that ignores the toString, equals, finalize and\n * hashCode method otherwise the test output in Maven looks strange and\n * replayAll/verifyAll doesn't work as expected.\n */\npublic class TestNGMethodFilter implements MethodFilter {\n    @Override\n    public boolean isHandled(Method method) {\n        return !isToString(method) && !isHashCode(method) && !isFinalize(method) && !isEquals(method);\n    }\n\n    private boolean isEquals(Method method) {\n        return method.getName().equals(\"equals\") && isOneArgumentMethodOfType(method, Object.class);\n    }\n\n    private boolean isFinalize(Method method) {\n        return method.getName().equals(\"finalize\") && isZeroArgumentMethod(method);\n    }\n\n    private boolean isHashCode(Method method) {\n        return method.getName().equals(\"hashCode\") && isZeroArgumentMethod(method);\n    }\n\n    private boolean isToString(Method method) {\n        return (method.getName().equals(\"toString\") && isZeroArgumentMethod(method));\n    }\n\n    private boolean isZeroArgumentMethod(Method method) {\n        return hasArgumentLength(method, 0);\n    }\n\n    private boolean hasArgumentLength(Method method, int length) {\n        return method.getParameterTypes().length == length;\n    }\n\n    private boolean isOneArgumentMethodOfType(Method method, Class<?> type) {\n        return hasArgumentLength(method, 1) && Object.class.equals(method.getParameterTypes()[0]);\n    }\n}"
  },
  {
    "path": "powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMockClassLoaderFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.modules.testng.internal;\n\nimport org.powermock.core.classloader.MockClassLoaderFactory;\nimport org.powermock.tests.utils.ArrayMerger;\nimport org.powermock.tests.utils.IgnorePackagesExtractor;\nimport org.powermock.tests.utils.impl.ArrayMergerImpl;\nimport org.powermock.tests.utils.impl.PowerMockIgnorePackagesExtractorImpl;\n\nclass TestNGMockClassLoaderFactory {\n    \n    private final IgnorePackagesExtractor ignorePackagesExtractor;\n    private final IgnorePackagesExtractor expectedExceptionsExtractor;\n    private final ArrayMerger arrayMerger;\n    \n    TestNGMockClassLoaderFactory() {\n        ignorePackagesExtractor = new PowerMockIgnorePackagesExtractorImpl();\n        expectedExceptionsExtractor = new PowerMockExpectedExceptionsExtractorImpl();\n        arrayMerger = new ArrayMergerImpl();\n    }\n    \n    \n    ClassLoader createClassLoader(Class<?> testClass) {\n        final String[] packagesToIgnore = arrayMerger.mergeArrays(\n            String.class,\n            ignorePackagesExtractor.getPackagesToIgnore(testClass),\n            expectedExceptionsExtractor.getPackagesToIgnore(testClass)\n        );\n        return new MockClassLoaderFactory(testClass, packagesToIgnore).createForClass(null);\n    }\n    \n}\n"
  },
  {
    "path": "powermock-modules/powermock-module-testng-agent/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.testng;\n\nimport org.powermock.core.agent.JavaAgentClassRegister;\nimport org.powermock.modules.agent.PowerMockAgent;\nimport org.powermock.modules.agent.support.JavaAgentClassRegisterImpl;\nimport org.powermock.modules.agent.support.PowerMockAgentTestInitializer;\nimport org.testng.IObjectFactory;\nimport org.testng.internal.ObjectFactoryImpl;\n\nimport java.lang.reflect.Constructor;\n\n/**\n * The PowerMock object factory for PowerMock java agent.\n */\npublic class PowerMockObjectFactory implements IObjectFactory {\n\n    static {\n        if (PowerMockObjectFactory.class.getClassLoader() != ClassLoader.getSystemClassLoader()) {\n            throw new IllegalStateException(\"PowerMockObjectFactory can only be used with the system classloader but was loaded by \" + PowerMockObjectFactory.class.getClassLoader());\n        }\n        PowerMockAgent.initializeIfPossible();\n    }\n\n    private final ObjectFactoryImpl defaultObjectFactory;\n\n    public PowerMockObjectFactory() {\n        defaultObjectFactory = new ObjectFactoryImpl();\n    }\n\n    @Override\n    public Object newInstance(Constructor constructor, Object... params) {\n        final Class<?> testClass = constructor.getDeclaringClass();\n        JavaAgentClassRegister agentClassRegister = new JavaAgentClassRegisterImpl();\n        PowerMockAgentTestInitializer.initialize(testClass, agentClassRegister);\n        return defaultObjectFactory.newInstance(constructor, params);\n    }\n}"
  },
  {
    "path": "powermock-modules/powermock-module-testng-common/src/main/java/org/powermock/modules/testng/PowerMockTestCase.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.modules.testng;\n\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.reflect.Whitebox;\nimport org.testng.IObjectFactory;\nimport org.testng.ITestContext;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.ObjectFactory;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\n/**\n * A PowerMock base class that <i>may</i> be used as a base class for all TestNG\n * test cases that uses PowerMock.\n */\npublic class PowerMockTestCase {\n\n    private Object annotationEnabler;\n\n    private ClassLoader previousCl = null;\n\n    public PowerMockTestCase() {\n        try {\n            Class<?> annotationEnablerClass = Class.forName(\"org.powermock.api.extension.listener.AnnotationEnabler\");\n            annotationEnabler = Whitebox.newInstance(annotationEnablerClass);\n        } catch (ClassNotFoundException e) {\n            annotationEnabler = null;\n        }\n    }\n\n    @BeforeClass\n    protected void beforePowerMockTestClass() throws Exception {\n        // To make sure that the mock repository is not in an incorrect state when the test begins\n        MockRepository.clear();\n        if(isLoadedByPowerMockClassloader()) {\n            final Thread thread = Thread.currentThread();\n            previousCl = thread.getContextClassLoader();\n            thread.setContextClassLoader(this.getClass().getClassLoader());\n        }\n    }\n\n    @AfterClass\n    protected void afterPowerMockTestClass() throws Exception {\n        if(previousCl != null) {\n            Thread.currentThread().setContextClassLoader(previousCl);\n        }\n    }\n\n\n    /**\n     * Must be executed before each test method. This method does the following:\n     * <ol>\n     * <li>Injects all mock fields (if they haven't been injected already)</li>\n     * </ol>\n     *\n     *\n     *\n     * @throws Exception\n     *             If something unexpected goes wrong.\n     */\n    @BeforeMethod\n    protected void beforePowerMockTestMethod() throws Exception {\n        injectMocks();\n    }\n\n    /**\n     * Must be executed after each test method. This method does the following:\n     * <ol>\n     * <li>Clear all injection fields (those annotated with a Mock annotation)</li>\n     * <li>Clears the PowerMock MockRepository</li>\n     * </ol>\n     *\n     * @throws Exception if something unexpected goes wrong.\n     */\n    @AfterMethod\n    protected void afterPowerMockTestMethod() throws Exception {\n        try {\n            clearMockFields();\n        } finally {\n            MockRepository.clear();\n        }\n    }\n\n    /**\n     * @param context the test context.\n     * @return The PowerMock object factory.\n     */\n    @ObjectFactory\n    public IObjectFactory create(ITestContext context) {\n        try {\n            final Class<?> powerMockObjectFactory = Class.forName(\"org.powermock.modules.testng.PowerMockObjectFactory\");\n            return (IObjectFactory) powerMockObjectFactory.newInstance();\n        } catch (ClassNotFoundException e) {\n            throw new IllegalStateException(\"Missing org.powermock.modules.testng.PowerMockObjectFactory in classpath.\");\n        } catch (Exception e) {\n            throw new RuntimeException(\"PowerMock internal error\", e);\n        }\n    }\n\n    private void clearMockFields() throws Exception {\n        if (annotationEnabler != null) {\n            final Class<? extends Annotation>[] mockAnnotations = Whitebox.invokeMethod(annotationEnabler,\n                    \"getMockAnnotations\");\n            Set<Field> mockFields = Whitebox.getFieldsAnnotatedWith(this, mockAnnotations);\n            for (Field field : mockFields) {\n                field.set(this, null);\n            }\n        }\n    }\n\n    private void injectMocks() throws Exception {\n        if (annotationEnabler != null) {\n            Whitebox.invokeMethod(annotationEnabler, \"beforeTestMethod\", new Class<?>[] { Object.class, Method.class, Object[].class }, this, null,\n                    null);\n        }\n    }\n\n    private boolean isLoadedByPowerMockClassloader() {\n        return this.getClass().getClassLoader() instanceof MockClassLoader;\n    }\n\n}\n"
  },
  {
    "path": "powermock-reflect/build.gradle",
    "content": "\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect;\n\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport org.powermock.reflect.matching.FieldMatchingStrategy;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Set;\n\n/**\n * Various utilities for accessing internals of a class. Basically a simplified\n * reflection utility intended for tests.\n */\npublic class Whitebox {\n\n\t/**\n\t * Convenience method to get a field from a class type.\n\t * <p>\n\t * The method will first try to look for a declared field in the same class.\n\t * If the field is not declared in this class it will look for the field in\n\t * the super class. This will continue throughout the whole class hierarchy.\n\t * If the field is not found an {@link IllegalArgumentException} is thrown.\n\t * \n\t * @param type\n\t *            The type of the class where the method is located.\n\t * @param fieldName\n\t *            The method names.\n\t * @return A {@code java.lang.reflect.Field}.\n\t * @throws FieldNotFoundException\n\t *             If a field cannot be found in the hierarchy.\n\t */\n\tpublic static Field getField(Class<?> type, String fieldName) {\n\t\treturn WhiteboxImpl.getField(type, fieldName);\n\t}\n\n\t/**\n\t * Get an array of {@link Field}'s that matches the supplied list of field\n\t * names.\n\t * \n\t * @param clazz\n\t *            The class that should contain the fields.\n\t * @param fieldNames\n\t *            The names of the fields that will be returned.\n\t * @return An array of Field's. May be of length 0 but not {@code null}\n\t * \n\t */\n\tpublic static Field[] getFields(Class<?> clazz, String... fieldNames) {\n\t\treturn WhiteboxImpl.getFields(clazz, fieldNames);\n\t}\n\n\t/**\n\t * Convenience method to get a method from a class type without having to\n\t * catch the checked exceptions otherwise required. These exceptions are\n\t * wrapped as runtime exceptions.\n\t * <p>\n\t * The method will first try to look for a declared method in the same\n\t * class. If the method is not declared in this class it will look for the\n\t * method in the super class. This will continue throughout the whole class\n\t * hierarchy. If the method is not found an {@link IllegalArgumentException}\n\t * is thrown.\n\t * \n\t * @param type\n\t *            The type of the class where the method is located.\n\t * @param methodName\n\t *            The method names.\n\t * @param parameterTypes\n\t *            All parameter types of the method (may be {@code null}).\n\t * @return A {@code java.lang.reflect.Method}.\n\t * @throws MethodNotFoundException\n\t *             If a method cannot be found in the hierarchy.\n\t */\n\tpublic static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) {\n\t\treturn WhiteboxImpl.getMethod(type, methodName, parameterTypes);\n\t}\n\n\t/**\n\t * Convenience method to get a method from a class type without having to\n\t * catch the checked exceptions otherwise required. These exceptions are\n\t * wrapped as runtime exceptions.\n\t * <p>\n\t * The method will first try to look for a declared method in the same\n\t * class. If the method is not declared in this class it will look for the\n\t * method in the super class. This will continue throughout the whole class\n\t * hierarchy. If the method is not found an {@link MethodNotFoundException}\n\t * is thrown. Since the method name is not specified an\n\t * {@link TooManyMethodsFoundException} is thrown if two or more methods\n\t * matches the same parameter types in the same class.\n\t * \n\t * @param type\n\t *            The type of the class where the method is located.\n\t * @param parameterTypes\n\t *            All parameter types of the method (may be {@code null}).\n\t * @return A {@code java.lang.reflect.Method}.\n\t * @throws MethodNotFoundException\n\t *             If a method cannot be found in the hierarchy.\n\t * @throws TooManyMethodsFoundException\n\t *             If several methods were found.\n\t */\n\tpublic static Method getMethod(Class<?> type, Class<?>... parameterTypes) {\n\t\treturn WhiteboxImpl.getMethod(type, parameterTypes);\n\t}\n\n\t/**\n\t * Create a new instance of a class without invoking its constructor.\n\t * <p>\n\t * No byte-code manipulation is needed to perform this operation and thus\n\t * it's not necessary use the {@code PowerMockRunner} or\n\t * {@code PrepareForTest} annotation to use this functionality.\n\t * \n\t * @param <T>\n\t *            The type of the instance to create.\n\t * @param classToInstantiate\n\t *            The type of the instance to create.\n\t * @return A new instance of type T, created without invoking the\n\t *         constructor.\n\t */\n\tpublic static <T> T newInstance(Class<T> classToInstantiate) {\n\t\treturn WhiteboxImpl.newInstance(classToInstantiate);\n\t}\n\n\t/**\n\t * Convenience method to get a (declared) constructor from a class type\n\t * without having to catch the checked exceptions otherwise required. These\n\t * exceptions are wrapped as runtime exceptions. The constructor is also set\n\t * to accessible.\n\t * \n\t * @param type\n\t *            The type of the class where the constructor is located.\n\t * @param parameterTypes\n\t *            All parameter types of the constructor (may be\n\t *            {@code null}).\n\t * @return A {@code java.lang.reflect.Constructor}.\n\t * @throws ConstructorNotFoundException\n\t *             if the constructor cannot be found.\n\t */\n\tpublic static <T> Constructor<T> getConstructor(Class<?> type, Class<?>... parameterTypes) {\n\t\treturn (Constructor<T>) WhiteboxImpl.getConstructor(type, parameterTypes);\n\t}\n\n\t/**\n\t * Set the value of a field using reflection. This method will traverse the\n\t * super class hierarchy until a field with name <tt>fieldName</tt> is\n\t * found.\n\t * \n\t * @param object\n\t *            the object whose field to modify\n\t * @param fieldName\n\t *            the name of the field\n\t * @param value\n\t *            the new value of the field\n\t */\n\tpublic static void setInternalState(Object object, String fieldName, Object value) {\n\t\tWhiteboxImpl.setInternalState(object, fieldName, value);\n\t}\n\n\t/**\n\t * Set an array value of a field using reflection. This method will traverse\n\t * the super class hierarchy until a field with name <tt>fieldName</tt> is\n\t * found.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param fieldName\n\t *            the name of the field\n\t * @param value\n\t *            the new value of the field\n\t */\n\tpublic static void setInternalState(Object object, String fieldName, Object[] value) {\n\t\tWhiteboxImpl.setInternalState(object, fieldName, value);\n\t}\n\n\t/**\n\t * Set the value of a field using reflection. This method will traverse the\n\t * super class hierarchy until the first field assignable to the\n\t * <tt>value</tt> type is found. The <tt>value</tt> (or\n\t * <tt>additionaValues</tt> if present) will then be assigned to this field.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param value\n\t *            the new value of the field\n\t * @param additionalValues\n\t *            Additional values to set on the object\n\t */\n\tpublic static void setInternalState(Object object, Object value, Object... additionalValues) {\n\t\tWhiteboxImpl.setInternalState(object, value, additionalValues);\n\t}\n\n\t/**\n\t * Set the value of a field using reflection at at specific place in the\n\t * class hierarchy (<tt>where</tt>). This first field assignable to\n\t * <tt>object</tt> will then be set to <tt>value</tt>.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param value\n\t *            the new value of the field\n\t * @param where\n\t *            the class in the hierarchy where the field is defined\n\t */\n\tpublic static void setInternalState(Object object, Object value, Class<?> where) {\n\t\tWhiteboxImpl.setInternalState(object, value, where);\n\t}\n\n\t/**\n\t * Set the value of a field using reflection. Use this method when you need\n\t * to specify in which class the field is declared. This might be useful\n\t * when you have mocked the instance you are trying to modify.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param fieldName\n\t *            the name of the field\n\t * @param value\n\t *            the new value of the field\n\t * @param where\n\t *            the class in the hierarchy where the field is defined\n\t */\n\tpublic static void setInternalState(Object object, String fieldName, Object value, Class<?> where) {\n\t\tWhiteboxImpl.setInternalState(object, fieldName, value, where);\n\t}\n\n\t/**\n\t * Set the value of a field using reflection. This method will traverse the\n\t * super class hierarchy until the first field of type <tt>fieldType</tt> is\n\t * found. The <tt>value</tt> will then be assigned to this field.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param fieldType\n\t *            the type of the field\n\t * @param value\n\t *            the new value of the field\n\t */\n\tpublic static void setInternalState(Object object, Class<?> fieldType, Object value) {\n\t\tWhiteboxImpl.setInternalState(object, fieldType, value);\n\t}\n\n\t/**\n\t * Set the value of a field using reflection at a specific location (\n\t * <tt>where</tt>) in the class hierarchy. The <tt>value</tt> will then be\n\t * assigned to this field. The first field matching the <tt>fieldType</tt>\n\t * in the hierarchy will be set.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param fieldType\n\t *            the type of the field the should be set.\n\t * @param value\n\t *            the new value of the field\n\t * @param where\n\t *            which class in the hierarchy defining the field\n\t */\n\tpublic static void setInternalState(Object object, Class<?> fieldType, Object value, Class<?> where) {\n\t\tWhiteboxImpl.setInternalState(object, fieldType, value, where);\n\t}\n\n\t/**\n\t * Get the value of a field using reflection. This method will iterate\n\t * through the entire class hierarchy and return the value of the first\n\t * field named <tt>fieldName</tt>. If you want to get a specific field value\n\t * at specific place in the class hierarchy please refer to\n\t * {@link #getInternalState(Object, String, Class)}.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param fieldName\n\t *            the name of the field\n\t */\n\tpublic static <T> T getInternalState(Object object, String fieldName) {\n\t\treturn WhiteboxImpl.getInternalState(object, fieldName);\n\t}\n\n\t/**\n\t * Get the value of a field using reflection. Use this method when you need\n\t * to specify in which class the field is declared. This might be useful\n\t * when you have mocked the instance you are trying to access.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param fieldName\n\t *            the name of the field\n\t * @param where\n\t *            which class the field is defined\n\t */\n\tpublic static <T> T getInternalState(Object object, String fieldName, Class<?> where) {\n\t\treturn WhiteboxImpl.getInternalState(object, fieldName, where);\n\t}\n\n\t/**\n\t * Get the value of a field using reflection. Use this method when you need\n\t * to specify in which class the field is declared. This might be useful\n\t * when you have mocked the instance you are trying to access. Use this\n\t * method to avoid casting.\n\t * \n\t * @deprecated Use {@link #getInternalState(Object, String, Class)} instead.\n\t * \n\t * @param <T>\n\t *            the expected type of the field\n\t * @param object\n\t *            the object to modify\n\t * @param fieldName\n\t *            the name of the field\n\t * @param where\n\t *            which class the field is defined\n\t * @param type\n\t *            the expected type of the field\n\t */\n\t@Deprecated\n\tpublic static <T> T getInternalState(Object object, String fieldName, Class<?> where, Class<T> type) {\n\t\treturn Whitebox.getInternalState(object, fieldName, where);\n\t}\n\n\t/**\n\t * Get the value of a field using reflection based on the fields type. This\n\t * method will traverse the super class hierarchy until the first field of\n\t * type <tt>fieldType</tt> is found. The value of this field will be\n\t * returned.\n\t * \n\t * @param object\n\t *            the object to modify\n\t * @param fieldType\n\t *            the type of the field\n\t */\n\tpublic static <T> T getInternalState(Object object, Class<T> fieldType) {\n\t\treturn WhiteboxImpl.getInternalState(object, fieldType);\n\n\t}\n\n\t/**\n\t * Get the value of a field using reflection based on the field type. Use\n\t * this method when you need to specify in which class the field is\n\t * declared. The first field matching the <tt>fieldType</tt> in\n\t * <tt>where</tt> is the field whose value will be returned.\n\t * \n\t * @param <T>\n\t *            the expected type of the field\n\t * @param object\n\t *            the object to modify\n\t * @param fieldType\n\t *            the type of the field\n\t * @param where\n\t *            which class the field is defined\n\t */\n\tpublic static <T> T getInternalState(Object object, Class<T> fieldType, Class<?> where) {\n\t\treturn WhiteboxImpl.getInternalState(object, fieldType, where);\n\t}\n\n\t/**\n\t * Invoke a private or inner class method without the need to specify the\n\t * method name. This is thus a more refactor friendly version of the\n\t * {@link #invokeMethod(Object, String, Object...)} method and is recommend\n\t * over this method for that reason. This method might be useful to test\n\t * private methods.\n\t * \n\t * @throws Exception if something wrong.\n\t */\n\tpublic static synchronized <T> T invokeMethod(Object instance, Object... arguments) throws Exception {\n\t\treturn WhiteboxImpl.invokeMethod(instance, arguments);\n\t}\n\n\t/**\n\t * Invoke a private or inner class static method without the need to specify\n\t * the method name. This is thus a more refactor friendly version of the\n\t * {@link #invokeMethod(Class, String, Object...)} method and is recommend\n\t * over this method for that reason. This method might be useful to test\n\t * private methods.\n\t * \n\t */\n\tpublic static synchronized <T> T invokeMethod(Class<?> klass, Object... arguments) throws Exception {\n\t\treturn WhiteboxImpl.invokeMethod(klass, arguments);\n\t}\n\n\t/**\n\t * Invoke a private or inner class method. This might be useful to test\n\t * private methods.\n\t */\n\tpublic static synchronized <T> T invokeMethod(Object instance, String methodToExecute, Object... arguments)\n\t\t\tthrows Exception {\n\t\treturn WhiteboxImpl.invokeMethod(instance, methodToExecute, arguments);\n\t}\n\n\t/**\n\t * Invoke a private or inner class method in cases where PowerMock cannot\n\t * automatically determine the type of the parameters, for example when\n\t * mixing primitive types and wrapper types in the same method. For most\n\t * situations use {@link #invokeMethod(Object, Object...)} instead.\n\t * \n\t * @throws Exception\n\t *             Exception that may occur when invoking this method.\n\t */\n\tpublic static synchronized <T> T invokeMethod(Object instance, String methodToExecute, Class<?>[] argumentTypes,\n\t\t\tObject... arguments) throws Exception {\n\t\treturn WhiteboxImpl.invokeMethod(instance, methodToExecute, argumentTypes, arguments);\n\t}\n\n\t/**\n\t * Invoke a private or inner class method in a subclass (defined by\n\t * {@code definedIn}) in cases where PowerMock cannot automatically\n\t * determine the type of the parameters, for example when mixing primitive\n\t * types and wrapper types in the same method. For most situations use\n\t * {@link #invokeMethod(Object, Object...)} instead.\n\t * \n\t * @throws Exception\n\t *             Exception that may occur when invoking this method.\n\t */\n\tpublic static synchronized <T> T invokeMethod(Object instance, String methodToExecute, Class<?> definedIn,\n\t\t\tClass<?>[] argumentTypes, Object... arguments) throws Exception {\n\t\treturn WhiteboxImpl.invokeMethod(instance, methodToExecute, definedIn, argumentTypes, arguments);\n\t}\n\n\t/**\n\t * Invoke a private or inner class method in that is located in a subclass\n\t * of the instance. This might be useful to test private methods.\n\t * \n\t * @throws Exception\n\t *             Exception that may occur when invoking this method.\n\t */\n\tpublic static synchronized <T> T invokeMethod(Object instance, Class<?> declaringClass, String methodToExecute,\n\t\t\tObject... arguments) throws Exception {\n\t\treturn WhiteboxImpl.invokeMethod(instance, declaringClass, methodToExecute, arguments);\n\t}\n\n\t/**\n\t * Invoke a private or inner class method in that is located in a subclass\n\t * of the instance. This might be useful to test private methods.\n\t * <p>\n\t * Use this for overloaded methods.\n\t * \n\t * @throws Exception\n\t *             Exception that may occur when invoking this method.\n\t */\n\tpublic static synchronized <T> T invokeMethod(Object object, Class<?> declaringClass, String methodToExecute,\n\t\t\tClass<?>[] parameterTypes, Object... arguments) throws Exception {\n\t\treturn WhiteboxImpl.invokeMethod(object, declaringClass, methodToExecute, parameterTypes, arguments);\n\t}\n\n\t/**\n\t * Invoke a static private or inner class method. This may be useful to test\n\t * private methods.\n\t * \n\t */\n\tpublic static synchronized <T> T invokeMethod(Class<?> clazz, String methodToExecute, Object... arguments)\n\t\t\tthrows Exception {\n\t\treturn WhiteboxImpl.invokeMethod(clazz, methodToExecute, arguments);\n\t}\n\n\t/**\n\t * Invoke a constructor. Useful for testing classes with a private\n\t * constructor when PowerMock cannot determine which constructor to invoke.\n\t * This only happens if you have two constructors with the same number of\n\t * arguments where one is using primitive data types and the other is using\n\t * the wrapped counter part. For example:\n\t * \n\t * <pre>\n\t * public class MyClass {\n\t *     private MyClass(Integer i) {\n\t *         ...\n\t *     } \n\t * \n\t *     private MyClass(int i) {\n\t *         ...\n\t *     }\n\t * </pre>\n\t * \n\t * This ought to be a really rare case. So for most situation, use\n\t * {@link #invokeConstructor(Class, Object...)} instead.\n\t * \n\t * \n\t * @return The object created after the constructor has been invoked.\n\t * @throws Exception\n\t *             If an exception occur when invoking the constructor.\n\t */\n\tpublic static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Class<?>[] parameterTypes,\n\t\t\tObject[] arguments) throws Exception {\n\t\treturn WhiteboxImpl.invokeConstructor(classThatContainsTheConstructorToTest, parameterTypes, arguments);\n\t}\n\n\t/**\n\t * Invoke a constructor. Useful for testing classes with a private\n\t * constructor.\n\t * \n\t * \n\t * @return The object created after the constructor has been invoked.\n\t * @throws Exception\n\t *             If an exception occur when invoking the constructor.\n\t */\n\tpublic static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Object... arguments)\n\t\t\tthrows Exception {\n\t\treturn WhiteboxImpl.invokeConstructor(classThatContainsTheConstructorToTest, arguments);\n\t}\n\n\t/**\n\t * Get the first parent constructor defined in a super class of\n\t * {@code klass}.\n\t * \n\t * @param klass\n\t *            The class where the constructor is located. {@code null}\n\t *            ).\n\t * @return A {@code java.lang.reflect.Constructor}.\n\t */\n\tpublic static Constructor<?> getFirstParentConstructor(Class<?> klass) {\n\t\treturn WhiteboxImpl.getFirstParentConstructor(klass);\n\t}\n\n\t/**\n\t * Get an array of {@link Method}'s that matches the supplied list of method\n\t * names. Both instance and static methods are taken into account.\n\t * \n\t * @param clazz\n\t *            The class that should contain the methods.\n\t * @param methodNames\n\t *            Names of the methods that will be returned.\n\t * @return An array of Method's.\n\t * @throws MethodNotFoundException\n\t *             If no method was found.\n\t */\n\tpublic static Method[] getMethods(Class<?> clazz, String... methodNames) {\n\t\treturn WhiteboxImpl.getMethods(clazz, methodNames);\n\t}\n\n\t/**\n\t * @return The type of the of an object.\n\t */\n\tpublic static Class<?> getType(Object object) {\n\t\treturn WhiteboxImpl.getType(object);\n\t}\n\n\t/**\n\t * Gets the type.\n\t *\n\t * @param object the object\n\t * @return The type of the of an object.\n\t */\n\tpublic static Class<?> getUnproxyType(Object object) {\n\t\treturn WhiteboxImpl.getUnproxyType(object);\n\t}\n\n\t/**\n\t * Get all fields annotated with a particular annotation. This method\n\t * traverses the class hierarchy when checking for the annotation.\n\t * \n\t * @param object\n\t *            The object to look for annotations. Note that if're you're\n\t *            passing an object only instance fields are checked, passing a\n\t *            class will only check static fields.\n\t * @param annotation\n\t *            The annotation type to look for.\n\t * @param additionalAnnotations\n\t *            Optionally more annotations to look for. If any of the\n\t *            annotations are associated with a particular field it will be\n\t *            added to the resulting {@code Set}.\n\t * @return A set of all fields containing the particular annotation.\n\t */\n\tpublic static Set<Field> getFieldsAnnotatedWith(Object object, Class<? extends Annotation> annotation,\n\t\t\tClass<? extends Annotation>... additionalAnnotations) {\n\t\treturn WhiteboxImpl.getFieldsAnnotatedWith(object, annotation, additionalAnnotations);\n\t}\n\n\t/**\n\t * Get all fields annotated with a particular annotation. This method\n\t * traverses the class hierarchy when checking for the annotation.\n\t * \n\t * @param object\n\t *            The object to look for annotations. Note that if're you're\n\t *            passing an object only instance fields are checked, passing a\n\t *            class will only check static fields.\n\t * @param annotationTypes\n\t *            The annotation types to look for\n\t * @return A set of all fields containing the particular annotation(s).\n\t * @since 1.3\n\t */\n\tpublic static Set<Field> getFieldsAnnotatedWith(Object object, Class<? extends Annotation>[] annotationTypes) {\n\t\treturn WhiteboxImpl.getFieldsAnnotatedWith(object, annotationTypes);\n\t}\n\n\t/**\n\t * Get all instance fields for a particular object. It returns all fields\n\t * regardless of the field modifier and regardless of where in the class\n\t * hierarchy a field is located.\n\t * \n\t * @param object\n\t *            The object whose instance fields to get.\n\t * @return All instance fields in the hierarchy. All fields are set to\n\t *         accessible\n\t */\n\tpublic static Set<Field> getAllInstanceFields(Object object) {\n\t\treturn WhiteboxImpl.getAllInstanceFields(object);\n\t}\n\n\t/**\n\t * Get all static fields for a particular type.\n\t * \n\t * @param type\n\t *            The class whose static fields to get.\n\t * @return All static fields in {@code type}. All fields are set to\n\t *         accessible.\n\t */\n\tpublic static Set<Field> getAllStaticFields(Class<?> type) {\n\t\treturn WhiteboxImpl.getAllStaticFields(type);\n\t}\n\n\t/**\n\t * Get all fields assignable from a particular type. This method traverses\n\t * the class hierarchy when checking for the type.\n\t * \n\t * @param object\n\t *            The object to look for type. Note that if're you're passing an\n\t *            object only instance fields are checked, passing a class will\n\t *            only check static fields.\n\t * @param type\n\t *            The type to look for.\n\t * @return A set of all fields of the particular type.\n\t */\n\tpublic static Set<Field> getFieldsOfType(Object object, Class<?> type) {\n\t\treturn WhiteboxImpl.getFieldsOfType(object, type);\n\t}\n\n\t/**\n\t * Get an inner class type\n\t * \n\t * @param declaringClass\n\t *            The class in which the inner class is declared.\n\t * @param name\n\t *            The unqualified name (simple name) of the inner class.\n\t * @return The type.\n\t */\n\tpublic static Class<Object> getInnerClassType(Class<?> declaringClass, String name) throws ClassNotFoundException {\n\t\treturn WhiteboxImpl.getInnerClassType(declaringClass, name);\n\t}\n\n\t/**\n\t * Get the type of a local inner class.\n\t * \n\t * @param declaringClass\n\t *            The class in which the local inner class is declared.\n\t * @param occurrence\n\t *            The occurrence of the local class. For example if you have two\n\t *            local classes in the {@code declaringClass} you must pass\n\t *            in {@code 1} if you want to get the type for the first\n\t *            one or {@code 2} if you want the second one.\n\t * @param name\n\t *            The unqualified name (simple name) of the local class.\n\t * @return The type.\n\t */\n\tpublic static Class<Object> getLocalClassType(Class<?> declaringClass, int occurrence, String name)\n\t\t\tthrows ClassNotFoundException {\n\t\treturn WhiteboxImpl.getLocalClassType(declaringClass, occurrence, name);\n\t}\n\n\t/**\n\t * Get the type of an anonymous inner class.\n\t * \n\t * @param declaringClass\n\t *            The class in which the anonymous inner class is declared.\n\t * @param occurrence\n\t *            The occurrence of the anonymous inner class. For example if\n\t *            you have two anonymous inner classes classes in the\n\t *            {@code declaringClass} you must pass in {@code 1} if\n\t *            you want to get the type for the first one or {@code 2}\n\t *            if you want the second one.\n\t * @return The type.\n\t */\n\tpublic static Class<Object> getAnonymousInnerClassType(Class<?> declaringClass, int occurrence)\n\t\t\tthrows ClassNotFoundException {\n\t\treturn WhiteboxImpl.getAnonymousInnerClassType(declaringClass, occurrence);\n\t}\n\n\t/**\n\t * Set the values of multiple instance fields defined in a context using\n\t * reflection. The values in the context will be assigned to values on the\n\t * {@code instance}. This method will traverse the class hierarchy when\n\t * searching for the fields. Example usage:\n\t * <p>\n\t * Given:\n\t * \n\t * <pre>\n\t * public class MyContext {\n\t * \tprivate String myString = &quot;myString&quot;;\n\t * \tprotected int myInt = 9;\n\t * }\n\t * \n\t * public class MyInstance {\n\t * \tprivate String myInstanceString;\n\t * \tprivate int myInstanceInt;\n\t * \n\t * }\n\t * </pre>\n\t * \n\t * then\n\t * \n\t * <pre>\n\t * Whitebox.setInternalStateFromContext(new MyInstance(), new MyContext());\n\t * </pre>\n\t * \n\t * will set the instance variables of {@code myInstance} to the values\n\t * specified in {@code MyContext}.\n\t * <p>\n\t * By default the {@link FieldMatchingStrategy#MATCHING} strategy is used\n\t * which means that the fields defined in the context but not found in the\n\t * <code>classOrInstance</code> are silently ignored.\n\t * \n\t * \n\t * \n\t * @param instance\n\t *            the object whose fields to modify.\n\t * @param context\n\t *            The context where the fields are defined.\n\t * @param additionalContexts\n\t *            Optionally more additional contexts.\n\t */\n\tpublic static void setInternalStateFromContext(Object instance, Object context, Object... additionalContexts) {\n\t\tWhiteboxImpl.setInternalStateFromContext(instance, context, additionalContexts);\n\t}\n\n\t/**\n\t * Set the values of multiple static fields defined in a context using\n\t * reflection. The values in the context will be assigned to values on the\n\t * {@code classOrInstance}. This method will traverse the class\n\t * hierarchy when searching for the fields. Example usage:\n\t * <p>\n\t * Given:\n\t * \n\t * <pre>\n\t * public class MyContext {\n\t * \tprivate static String myString = &quot;myString&quot;;\n\t * \tprotected static int myInt = 9;\n\t * }\n\t * \n\t * public class MyInstance {\n\t * \tprivate static String myInstanceString;\n\t * \tprivate static int myInstanceInt;\n\t * \n\t * }\n\t * </pre>\n\t * \n\t * then\n\t * \n\t * <pre>\n\t * Whitebox.setInternalStateFromContext(MyInstance.class, MyContext.class);\n\t * </pre>\n\t * \n\t * will set the static variables of {@code MyInstance} to the values\n\t * specified in {@code MyContext}.\n\t *<p>\n\t * By default the {@link FieldMatchingStrategy#MATCHING} strategy is used\n\t * which means that the fields defined in the context but not found in the\n\t * <code>classOrInstance</code> are silently ignored.\n\t * \n\t * @param classOrInstance\n\t *            The object or class whose fields to set.\n\t * @param context\n\t *            The context where the fields are defined.\n\t * @param additionalContexts\n\t *            Optionally more additional contexts.\n\t */\n\tpublic static void setInternalStateFromContext(Object classOrInstance, Class<?> context,\n\t\t\tClass<?>... additionalContexts) {\n\t\tWhiteboxImpl.setInternalStateFromContext(classOrInstance, context, additionalContexts);\n\t}\n\n\t/**\n\t * Set the values of multiple instance fields defined in a context using\n\t * reflection and using an explicit {@link FieldMatchingStrategy}. The\n\t * values in the context will be assigned to values on the\n\t * {@code instance}. This method will traverse the class hierarchy when\n\t * searching for the fields. Example usage:\n\t * <p>\n\t * Given:\n\t * \n\t * <pre>\n\t * public class MyContext {\n\t * \tprivate String myString = &quot;myString&quot;;\n\t * \tprotected int myInt = 9;\n\t * }\n\t * \n\t * public class MyInstance {\n\t * \tprivate String myInstanceString;\n\t * \tprivate int myInstanceInt;\n\t * \n\t * }\n\t * </pre>\n\t * \n\t * then\n\t * \n\t * <pre>\n\t * Whitebox.setInternalStateFromContext(new MyInstance(), new MyContext());\n\t * </pre>\n\t * \n\t * will set the instance variables of {@code myInstance} to the values\n\t * specified in {@code MyContext}.\n\t * \n\t * @param instance\n\t *            the object whose fields to modify.\n\t * @param context\n\t *            The context where the fields are defined.\n\t * @param strategy\n\t *            Which field matching strategy to use.\n\t */\n\tpublic static void setInternalStateFromContext(Object instance, Object context, FieldMatchingStrategy strategy) {\n\t\tWhiteboxImpl.setInternalStateFromContext(instance, context, strategy);\n\t}\n\n\t/**\n\t * Set the values of multiple static fields defined in a context using\n\t * reflection and using an explicit {@link FieldMatchingStrategy}. The\n\t * values in the context will be assigned to values on the\n\t * {@code classOrInstance}. This method will traverse the class\n\t * hierarchy when searching for the fields. Example usage:\n\t * <p>\n\t * Given:\n\t * \n\t * <pre>\n\t * public class MyContext {\n\t * \tprivate static String myString = &quot;myString&quot;;\n\t * \tprotected static int myInt = 9;\n\t * }\n\t * \n\t * public class MyInstance {\n\t * \tprivate static String myInstanceString;\n\t * \tprivate static int myInstanceInt;\n\t * \n\t * }\n\t * </pre>\n\t * \n\t * then\n\t * \n\t * <pre>\n\t * Whitebox.setInternalStateFromContext(MyInstance.class, MyContext.class);\n\t * </pre>\n\t * \n\t * will set the static variables of {@code MyInstance} to the values\n\t * specified in {@code MyContext}.\n\t *<p>\n\t * \n\t * @param instance\n\t *            The object or class whose fields to set.\n\t * @param context\n\t *            The context where the fields are defined.\n\t * @param strategy\n     *              Which field matching strategy to use.\n\t */\n\tpublic static void setInternalStateFromContext(Object instance, Class<?> context, FieldMatchingStrategy strategy) {\n\t\tWhiteboxImpl.setInternalStateFromContext(instance, context, strategy);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/exceptions/ConstructorNotFoundException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.exceptions;\n\n/**\n * A run-time exception that may be thrown to indicate that a constructor was\n * not found.\n */\npublic class ConstructorNotFoundException extends RuntimeException {\n\tprivate static final long serialVersionUID = -7329106318739007850L;\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The cause\n\t * is not initialized, and may subsequently be initialized by a call to\n\t * {@link #initCause}.\n\t * \n\t * @param message\n\t *            the detail message. The detail message is saved for later\n\t *            retrieval by the {@link #getMessage()} method.\n\t */\n\tpublic ConstructorNotFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n\t/**\n\t * Constructs a new runtime exception with the specified detail message and\n\t * cause.\n\t * <p>\n\t * Note that the detail message associated with {@code cause} is\n\t * <i>not</i> automatically incorporated in this exception's detail message.\n\t * \n\t * @param message\n\t *            the detail message (which is saved for later retrieval by the\n\t *            {@link #getMessage()} method).\n\t * @param cause\n\t *            the cause (which is saved for later retrieval by the\n\t *            {@link #getCause()} method). (A <tt>null</tt> value is\n\t *            permitted, and indicates that the cause is nonexistent or\n\t *            unknown.)\n\t */\n\tpublic ConstructorNotFoundException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/exceptions/FieldNotFoundException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.exceptions;\n\n/**\n * A run-time exception that may be thrown to indicate that a field was not\n * found.\n */\npublic class FieldNotFoundException extends RuntimeException {\n\tprivate static final long serialVersionUID = 5420195402982130931L;\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The cause\n\t * is not initialized, and may subsequently be initialized by a call to\n\t * {@link #initCause}.\n\t * \n\t * @param message\n\t *            the detail message. The detail message is saved for later\n\t *            retrieval by the {@link #getMessage()} method.\n\t */\n\tpublic FieldNotFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/exceptions/MethodInvocationException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.exceptions;\n\n/**\n * A run-time exception that may be thrown to indicate that a method invocation\n * failed.\n */\npublic class MethodInvocationException extends RuntimeException {\n\tprivate static final long serialVersionUID = 4051932931902248488L;\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The cause\n\t * is not initialized, and may subsequently be initialized by a call to\n\t * {@link #initCause}.\n\t * \n\t * @param message\n\t *            the detail message. The detail message is saved for later\n\t *            retrieval by the {@link #getMessage()} method.\n\t */\n\tpublic MethodInvocationException(String message) {\n\t\tsuper(message);\n\t}\n\n\t/**\n\t * Constructs a new runtime exception with the specified detail message and\n\t * cause.\n\t * <p>\n\t * Note that the detail message associated with {@code cause} is\n\t * <i>not</i> automatically incorporated in this exception's detail message.\n\t * \n\t * @param message\n\t *            the detail message (which is saved for later retrieval by the\n\t *            {@link #getMessage()} method).\n\t * @param cause\n\t *            the cause (which is saved for later retrieval by the\n\t *            {@link #getCause()} method). (A <tt>null</tt> value is\n\t *            permitted, and indicates that the cause is nonexistent or\n\t *            unknown.)\n\t */\n\tpublic MethodInvocationException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified cause and a detail message\n\t * of <tt>(cause==null ? null : cause.toString())</tt> (which typically\n\t * contains the class and detail message of <tt>cause</tt>). This\n\t * constructor is useful for runtime exceptions that are little more than\n\t * wrappers for other throwables.\n\t * \n\t * @param cause\n\t *            the cause (which is saved for later retrieval by the\n\t *            {@link #getCause()} method). (A <tt>null</tt> value is\n\t *            permitted, and indicates that the cause is nonexistent or\n\t *            unknown.)\n\t * @since 1.4\n\t */\n\tpublic MethodInvocationException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/exceptions/MethodNotFoundException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.exceptions;\n\n/**\n * A run-time exception that may be thrown to indicate that a method was not\n * found.\n */\npublic class MethodNotFoundException extends RuntimeException {\n\tprivate static final long serialVersionUID = -1617211962548265914L;\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The cause\n\t * is not initialized, and may subsequently be initialized by a call to\n\t * {@link #initCause}.\n\t * \n\t * @param message\n\t *            the detail message. The detail message is saved for later\n\t *            retrieval by the {@link #getMessage()} method.\n\t */\n\tpublic MethodNotFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/exceptions/TooManyConstructorsFoundException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.exceptions;\n\n/**\n * A run-time exception that may be thrown to indicate that too many\n * constructors were found.\n */\npublic class TooManyConstructorsFoundException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1365925879589152290L;\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The cause\n\t * is not initialized, and may subsequently be initialized by a call to\n\t * {@link #initCause}.\n\t * \n\t * @param message\n\t *            the detail message. The detail message is saved for later\n\t *            retrieval by the {@link #getMessage()} method.\n\t */\n\tpublic TooManyConstructorsFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/exceptions/TooManyFieldsFoundException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.exceptions;\n\n/**\n * A run-time exception that may be thrown to indicate that too many fields were\n * found.\n */\npublic class TooManyFieldsFoundException extends RuntimeException {\n\tprivate static final long serialVersionUID = 1564231184610341053L;\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The cause\n\t * is not initialized, and may subsequently be initialized by a call to\n\t * {@link #initCause}.\n\t * \n\t * @param message\n\t *            the detail message. The detail message is saved for later\n\t *            retrieval by the {@link #getMessage()} method.\n\t */\n\tpublic TooManyFieldsFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/exceptions/TooManyMethodsFoundException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.exceptions;\n\n/**\n * A run-time exception that may be thrown to indicate that too many methods\n * were found.\n */\npublic class TooManyMethodsFoundException extends RuntimeException {\n\tprivate static final long serialVersionUID = -3267907243933066607L;\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The cause\n\t * is not initialized, and may subsequently be initialized by a call to\n\t * {@link #initCause}.\n\t * \n\t * @param message\n\t *            the detail message. The detail message is saved for later\n\t *            retrieval by the {@link #getMessage()} method.\n\t */\n\tpublic TooManyMethodsFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/CandidateConstructorSearcher.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.reflect.internal;\n\nimport org.powermock.reflect.internal.comparator.ComparatorFactory;\n\nimport java.lang.reflect.Constructor;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n *  This class search the best candidate in the given class to invoke constructor with given parameters.\n */\nclass CandidateConstructorSearcher<T> {\n    private final Class<T> classThatContainsTheConstructorToTest;\n    private final Class<?>[] argumentTypes;\n\n    public CandidateConstructorSearcher(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes) {\n\n        this.classThatContainsTheConstructorToTest = classThatContainsTheConstructorToTest;\n        this.argumentTypes = argumentTypes;\n    }\n    \n    public Constructor<T> findConstructor() {\n        final Constructor<T>[] constructors = getConstructors();\n        if (constructors.length == 0) {\n            return null;\n        }\n        if (constructors.length == 1) {\n            return constructors[0];\n        } else {\n            return findBestCandidate(constructors);\n\n        }\n    }\n\n    private Constructor<T> findBestCandidate(Constructor<T>[] constructors) {\n        //We've found overloaded constructor, we need to find the best one to invoke.\n        Arrays.sort(constructors, ComparatorFactory.createConstructorComparator());\n        return constructors[0];\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    private Constructor<T>[] getConstructors() {\n\n        try {\n            Constructor<?>[] declaredConstructors = classThatContainsTheConstructorToTest.getDeclaredConstructors();\n            List<Constructor<?>> constructors = new ArrayList<Constructor<?>>();\n            for (Constructor<?> constructor : declaredConstructors) {\n                if (argumentsApplied(constructor)) {\n                    constructors.add(constructor);\n                }\n            }\n            return constructors.toArray(new Constructor[constructors.size()]);\n        } catch (Exception e) {\n            return new Constructor[0];\n        }\n\n    }\n\n    private boolean argumentsApplied(Constructor<?> constructor) {\n        Class<?>[] constructorArgumentTypes = constructor.getParameterTypes();\n        if (constructorArgumentTypes.length != argumentTypes.length) {\n            return false;\n        }\n\n        for (int index = 0; index < argumentTypes.length; index++) {\n            if (!constructorArgumentTypes[index].isAssignableFrom(argumentTypes[index])) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/Constructor.java",
    "content": "package org.powermock.reflect.internal;\n\nclass Constructor {\n\n    private final Class<?>[] parameterTypes;\n    private java.lang.reflect.Constructor constructor;\n    private boolean isVarArgs;\n\n    Constructor(java.lang.reflect.Constructor constructor) {\n        this.constructor = constructor;\n        this.parameterTypes = constructor.getParameterTypes();\n        this.isVarArgs = constructor.isVarArgs();\n    }\n\n    boolean canBeInvokeWith(Object[] arguments) {\n        return new ParametersMatcher(isVarArgs, parameterTypes, arguments).match();\n    }\n\n    public java.lang.reflect.Constructor<?> getJavaConstructor() {\n        return constructor;\n    }\n\n    public boolean isVarArg() {\n        return isVarArgs;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/ConstructorFinder.java",
    "content": "package org.powermock.reflect.internal;\n\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyConstructorsFoundException;\n\nimport java.lang.reflect.Modifier;\nimport java.util.HashSet;\nimport java.util.Set;\n\nclass ConstructorFinder {\n    private Class<?> type;\n    private Object[] arguments;\n    private Class<?> unmockedType;\n    private Constructor potentialConstructor;\n\n    ConstructorFinder(Class<?> type, Object... arguments) {\n        if (type == null) {\n            throw new IllegalArgumentException(\"Class type cannot be null.\");\n        }\n\n        this.type = type;\n        this.arguments = arguments;\n        this.unmockedType = WhiteboxImpl.getOriginalUnmockedType(type);\n\n        if (isNestedClass() && arguments != null) {\n            addArgumentForNestedClass();\n        }\n    }\n\n    public java.lang.reflect.Constructor findConstructor() {\n        lookupPotentialConstructor();\n        throwExceptionIfConstructorWasNotFound();\n        return potentialConstructor.getJavaConstructor();\n    }\n\n    private void lookupPotentialConstructor() {Set<Constructor> constructors = getDeclaredConstructorsWithoutPowerMockConstructor();\n\n        for (Constructor constructor : constructors) {\n            if (constructor.canBeInvokeWith(arguments)) {\n                setPotentialConstructor(constructor);\n            }\n\n            // if a constructor is found and it has varargs parameters then the constructor will be used even if\n            // other constructor is matcher the given arguments. It is done, because when Argument Matchers are used\n            // arguments passed to the method are null value and it's imposable to determinate whether parameters\n            // match to arguments or not.\n\n            if (isVarArgConstructorFound()){\n                return;\n            }\n        }\n    }\n\n    private boolean isVarArgConstructorFound() {return potentialConstructor!=null && potentialConstructor.isVarArg();}\n\n    private void setPotentialConstructor(Constructor constructor) {\n        if (potentialConstructor == null) {\n            potentialConstructor = constructor;\n        }else{\n                /*\n                       * We've already found a constructor match before, this\n                       * means that PowerMock cannot determine which method to\n                       * expect since there are two methods with the same name\n                       * and the same number of arguments but one is using\n                       * wrapper types.\n                       */\n            throwExceptionWhenMultipleConstructorMatchesFound(new java.lang.reflect.Constructor[]{potentialConstructor.getJavaConstructor(),\n                    constructor.getJavaConstructor()});\n        }\n    }\n\n    public void throwExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[] constructors) {\n        if (constructors == null || constructors.length < 2) {\n            throw new IllegalArgumentException(\"Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors.\");\n        }\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\\n\");\n        sb.append(\"Matching constructors in class \").append(constructors[0].getDeclaringClass().getName())\n          .append(\" were:\\n\");\n\n        for (java.lang.reflect.Constructor constructor : constructors) {\n            sb.append(constructor.getName()).append(\"( \");\n            final Class<?>[] parameterTypes = constructor.getParameterTypes();\n            for (Class<?> paramType : parameterTypes) {\n                sb.append(paramType.getName()).append(\".class \");\n            }\n            sb.append(\")\\n\");\n        }\n        throw new TooManyConstructorsFoundException(sb.toString());\n    }\n\n    private void addArgumentForNestedClass() {\n        Object[] argumentsForLocalClass = new Object[arguments.length + 1];\n        argumentsForLocalClass[0] = unmockedType.getEnclosingClass();\n        System.arraycopy(arguments, 0, argumentsForLocalClass, 1, arguments.length);\n        arguments = argumentsForLocalClass;\n    }\n\n    private boolean isNestedClass() {\n        return (unmockedType.isLocalClass() || unmockedType.isAnonymousClass() || unmockedType.isMemberClass())\n                       && !Modifier.isStatic(unmockedType.getModifiers());\n    }\n\n    private Set<Constructor> getDeclaredConstructorsWithoutPowerMockConstructor() {\n        Set<Constructor> constructors = new HashSet<Constructor>();\n        for (java.lang.reflect.Constructor<?> constructor : unmockedType.getDeclaredConstructors()) {\n            if (!isPowerMockConstructor(constructor.getParameterTypes())) {\n                constructors.add(new Constructor(constructor));\n            }\n        }\n        return constructors;\n    }\n\n    private boolean isPowerMockConstructor(Class<?>[] parameterTypes) {\n        return parameterTypes.length >= 1\n                    && parameterTypes[parameterTypes.length - 1].getName().equals(\n                \"org.powermock.core.IndicateReloadClass\");\n    }\n\n    private void throwExceptionIfConstructorWasNotFound() {\n        if (potentialConstructor == null) {\n            String message = \"No constructor found in class '\" + WhiteboxImpl.getOriginalUnmockedType(type).getName() + \"' \" +\n                                     \"with \"\n                                     + \"parameter types: [ \" + WhiteboxImpl.getArgumentTypesAsString(arguments) + \" ].\";\n            throw new ConstructorNotFoundException(message);\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/ParameterTypesMatcher.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.reflect.internal;\n\n/**\n *\n */\nclass ParameterTypesMatcher {\n    private boolean isVarArgs;\n    private Class<?>[] expectedParameterTypes;\n    private Class<?>[] actualParameterTypes;\n\n    public ParameterTypesMatcher(boolean isVarArgs, Class<?>[] expectedParameterTypes, Class<?>... actualParameterTypes) {\n        this.isVarArgs = isVarArgs;\n        this.expectedParameterTypes = expectedParameterTypes;\n        this.actualParameterTypes = actualParameterTypes;\n    }\n\n    private boolean isRemainParamsVarArgs(int index, Class<?> actualParameterType) {\n        return isVarArgs && index == expectedParameterTypes.length - 1\n                       && actualParameterType.getComponentType().isAssignableFrom(expectedParameterTypes[index]);\n    }\n\n    private boolean isParameterTypesNotMatch(Class<?> actualParameterType, Class<?> expectedParameterType) {\n        if (actualParameterType == null){\n            return false;\n        }\n        if (expectedParameterType == null){\n           return false;\n        }\n        return !actualParameterType.isAssignableFrom(expectedParameterType);\n    }\n\n    public boolean match() {\n        assertParametersTypesNotNull();\n        if (isParametersLengthMatch()) {\n            return false;\n        } else {\n            return isParametersMatch();\n        }\n    }\n\n    private boolean isParametersLengthMatch() {return expectedParameterTypes.length != actualParameterTypes.length;}\n\n    private void assertParametersTypesNotNull() {\n        if (expectedParameterTypes == null || actualParameterTypes == null) {\n            throw new IllegalArgumentException(\"parameter types cannot be null\");\n        }\n    }\n\n    private Boolean isParametersMatch() {\n        for (int index = 0; index < expectedParameterTypes.length; index++) {\n            final Class<?> actualParameterType = actualParameterTypes[index];\n            if (isRemainParamsVarArgs(index, actualParameterType)) {\n                return true;\n            } else {\n                final Class<?> expectedParameterType = expectedParameterTypes[index];\n                if (isParameterTypesNotMatch(actualParameterType, expectedParameterType)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/ParametersMatcher.java",
    "content": "package org.powermock.reflect.internal;\n\n/**\n *\n */\nclass ParametersMatcher {\n    private final Class<?>[] parameterTypes;\n    private final Object[] arguments;\n    private boolean isVarArgs;\n\n    public ParametersMatcher(boolean isVarArgs, Class<?>[] parameterTypes, Object[] arguments) {\n        this.isVarArgs = isVarArgs;\n        this.parameterTypes = parameterTypes;\n        this.arguments = arguments;\n    }\n\n    public boolean match() {\n        if ((arguments != null && (parameterTypes.length == arguments.length))) {\n            if (parameterTypes.length == 0) {\n                return true;\n            }\n            return checkArgumentTypesMatchParameterTypes(isVarArgs, parameterTypes, arguments);\n        } else if (doesParameterTypesMatchForVarArgsInvocation(arguments)) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    boolean checkArgumentTypesMatchParameterTypes(boolean isVarArgs, Class<?>[] parameterTypes,\n                                                  Object[] arguments) {\n        if (parameterTypes == null) {\n            throw new IllegalArgumentException(\"parameter types cannot be null\");\n        } else if (!isVarArgs && arguments.length != parameterTypes.length) {\n            return false;\n        }\n        for (int i = 0; i < arguments.length; i++) {\n            Object argument = arguments[i];\n            if (argument == null) {\n                final int index;\n                if (i >= parameterTypes.length) {\n                    index = parameterTypes.length - 1;\n                } else {\n                    index = i;\n                }\n                final Class<?> type = parameterTypes[index];\n                if (type.isPrimitive()) {\n                    // Primitives cannot be null\n                    return false;\n                } else {\n                    continue;\n                }\n            } else if (i >= parameterTypes.length) {\n                if (WhiteboxImpl.isAssignableFrom(parameterTypes[parameterTypes.length - 1], WhiteboxImpl.getType(\n                        argument))) {\n                    continue;\n                } else {\n                    return false;\n                }\n            } else {\n                boolean assignableFrom = WhiteboxImpl.isAssignableFrom(parameterTypes[i], WhiteboxImpl.getType(\n                        argument));\n                final boolean isClass = parameterTypes[i].equals(Class.class) && WhiteboxImpl.isClass(argument);\n                if (!assignableFrom && !isClass) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n\n    boolean doesParameterTypesMatchForVarArgsInvocation(Object[] arguments) {\n        if (isVarArgs && arguments != null && arguments.length >= 1 && parameterTypes != null\n                    && parameterTypes.length >= 1) {\n            final Class<?> componentType = parameterTypes[parameterTypes.length - 1].getComponentType();\n            final Object lastArgument = arguments[arguments.length - 1];\n            if (lastArgument != null) {\n                final Class<?> lastArgumentTypeAsPrimitive = WhiteboxImpl.getTypeAsPrimitiveIfWrapped(lastArgument);\n                final Class<?> varArgsParameterTypeAsPrimitive = WhiteboxImpl.getTypeAsPrimitiveIfWrapped(componentType);\n                isVarArgs = varArgsParameterTypeAsPrimitive.isAssignableFrom(lastArgumentTypeAsPrimitive);\n            }\n        }\n        return isVarArgs && checkArgumentTypesMatchParameterTypes(isVarArgs, parameterTypes, arguments);\n\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/TypeUtils.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal;\n\n/**\n * Utilities for types.\n */\npublic class TypeUtils {\n\n\t/**\n\t * Get the default value for a type.\n\t * \n\t * @param type\n\t *            The type whose default value to get.\n\t * @return The default return type of {@code type}.\n\t */\n\tpublic static Object getDefaultValue(Class<?> type) {\n\t\treturn getDefaultValue(type.getName());\n\t}\n\n\t/**\n\t * Get the default value of a type with based on its fully-qualified name.\n\t * \n\t * @param fullyQualifiedTypeName\n\t *            The name of the type whose default value to get.\n\t * @return The default value of {@code fullyQualifiedTypeName}.\n\t */\n\tpublic static Object getDefaultValue(String fullyQualifiedTypeName) {\n\t\tif (fullyQualifiedTypeName == null) { // Void\n\t\t\treturn \"\";\n\t\t} else if (fullyQualifiedTypeName.equals(byte.class.getName())) {\n\t\t\treturn (byte) 0;\n\t\t} else if (fullyQualifiedTypeName.equals(int.class.getName())) {\n\t\t\treturn 0;\n\t\t} else if (fullyQualifiedTypeName.equals(short.class.getName())) {\n\t\t\treturn (short) 0;\n\t\t} else if (fullyQualifiedTypeName.equals(long.class.getName())) {\n\t\t\treturn 0L;\n\t\t} else if (fullyQualifiedTypeName.equals(float.class.getName())) {\n\t\t\treturn 0.0F;\n\t\t} else if (fullyQualifiedTypeName.equals(double.class.getName())) {\n\t\t\treturn 0.0D;\n\t\t} else if (fullyQualifiedTypeName.equals(boolean.class.getName())) {\n\t\t\treturn false;\n\t\t} else if (fullyQualifiedTypeName.equals(char.class.getName())) {\n\t\t\treturn ' ';\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the default value of a type with based on its fully-qualified name.\n\t * \n\t * @param fullyQualifiedTypeName\n\t *            The name of the type whose default value to get.\n\t * @return The default value of {@code fullyQualifiedTypeName}.\n\t */\n\tpublic static String getDefaultValueAsString(String fullyQualifiedTypeName) {\n\t\tif (fullyQualifiedTypeName == null) { // Void\n\t\t\treturn \"\";\n\t\t} else if (fullyQualifiedTypeName.equals(byte.class.getName())) {\n\t\t\treturn \"(byte) 0\";\n\t\t} else if (fullyQualifiedTypeName.equals(int.class.getName())) {\n\t\t\treturn \"0\";\n\t\t} else if (fullyQualifiedTypeName.equals(short.class.getName())) {\n\t\t\treturn \"(short) 0\";\n\t\t} else if (fullyQualifiedTypeName.equals(long.class.getName())) {\n\t\t\treturn \"0L\";\n\t\t} else if (fullyQualifiedTypeName.equals(float.class.getName())) {\n\t\t\treturn \"0.0F\";\n\t\t} else if (fullyQualifiedTypeName.equals(double.class.getName())) {\n\t\t\treturn \"0.0D\";\n\t\t} else if (fullyQualifiedTypeName.equals(boolean.class.getName())) {\n\t\t\treturn \"false\";\n\t\t} else if (fullyQualifiedTypeName.equals(char.class.getName())) {\n\t\t\treturn \"' '\";\n\t\t} else {\n\t\t\treturn \"null\";\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal;\n\nimport org.objenesis.Objenesis;\nimport org.objenesis.ObjenesisStd;\nimport org.objenesis.instantiator.ObjectInstantiator;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\nimport org.powermock.reflect.exceptions.MethodInvocationException;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyConstructorsFoundException;\nimport org.powermock.reflect.exceptions.TooManyFieldsFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\nimport org.powermock.reflect.internal.comparator.ComparatorFactory;\nimport org.powermock.reflect.internal.matcherstrategies.AllFieldsMatcherStrategy;\nimport org.powermock.reflect.internal.matcherstrategies.AssignableFromFieldTypeMatcherStrategy;\nimport org.powermock.reflect.internal.matcherstrategies.AssignableToFieldTypeMatcherStrategy;\nimport org.powermock.reflect.internal.matcherstrategies.FieldAnnotationMatcherStrategy;\nimport org.powermock.reflect.internal.matcherstrategies.FieldMatcherStrategy;\nimport org.powermock.reflect.internal.matcherstrategies.FieldNameMatcherStrategy;\nimport org.powermock.reflect.internal.primitivesupport.BoxedWrapper;\nimport org.powermock.reflect.internal.primitivesupport.PrimitiveWrapper;\nimport org.powermock.reflect.internal.proxy.ProxyFrameworks;\nimport org.powermock.reflect.internal.proxy.UnproxiedType;\nimport org.powermock.reflect.matching.FieldMatchingStrategy;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.lang.reflect.Proxy;\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport sun.misc.Unsafe;\n\n/**\n * Various utilities for accessing internals of a class. Basically a simplified\n * reflection utility intended for tests.\n */\npublic class WhiteboxImpl {\n\n    /**\n     * The proxy framework.\n     */\n    private static ProxyFrameworks proxyFrameworks = new ProxyFrameworks();\n\n    /**\n     * \"Strong\" map prevent class and method objects from being GCed and unloaded.\n     * TODO replace with ClassValue when Powermock drops Java 6 support.\n     */\n    private static ConcurrentMap<Class, Method[]> allClassMethodsCache = new ConcurrentHashMap<Class, Method[]>();\n\n    /**\n     * Convenience method to get a method from a class type without having to\n     * catch the checked exceptions otherwise required. These exceptions are\n     * wrapped as runtime exceptions.\n     *\n     * The method will first try to look for a declared method in the same\n     * class. If the method is not declared in this class it will look for the\n     * method in the super class. This will continue throughout the whole class\n     * hierarchy. If the method is not found an {@link MethodNotFoundException}\n     * is thrown. Since the method name is not specified an\n     *\n     * @param type           The type of the class where the method is located.\n     * @param parameterTypes All parameter types of the method (may be {@code null}).\n     * @return A . {@link TooManyMethodsFoundException} is thrown if two or more\n     * methods matches the same parameter types in the same class.\n     */\n    public static Method getMethod(Class<?> type, Class<?>... parameterTypes) {\n        Class<?> thisType = type;\n        if (parameterTypes == null) {\n            parameterTypes = new Class<?>[0];\n        }\n\n        List<Method> foundMethods = new LinkedList<Method>();\n        while (thisType != null) {\n            Method[] methodsToTraverse = null;\n            if (thisType.isInterface()) {\n                // Interfaces only contain public (and abstract) methods, no\n                // need to traverse the hierarchy.\n                methodsToTraverse = getAllPublicMethods(thisType);\n            } else {\n                methodsToTraverse = thisType.getDeclaredMethods();\n            }\n            for (Method method : methodsToTraverse) {\n                if (checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) {\n                    foundMethods.add(method);\n                    if (foundMethods.size() == 1) {\n                        method.setAccessible(true);\n                    }\n                }\n\n            }\n            if (foundMethods.size() == 1) {\n                return foundMethods.get(0);\n            } else if (foundMethods.size() > 1) {\n                break;\n            }\n            thisType = thisType.getSuperclass();\n        }\n\n        if (foundMethods.isEmpty()) {\n            throw new MethodNotFoundException(\"No method was found with parameter types: [ \"\n                                                      + getArgumentTypesAsString((Object[]) parameterTypes) + \" ] in class \"\n                                                      + getOriginalUnmockedType(type).getName() + \".\");\n        } else {\n            throwExceptionWhenMultipleMethodMatchesFound(\"method name\",\n                    foundMethods.toArray(new Method[foundMethods.size()]));\n        }\n        // Will never happen\n        return null;\n    }\n\n    /**\n     * Convenience method to get a method from a class type without having to\n     * catch the checked exceptions otherwise required. These exceptions are\n     * wrapped as runtime exceptions.\n     *\n     * The method will first try to look for a declared method in the same\n     * class. If the method is not declared in this class it will look for the\n     * method in the super class. This will continue throughout the whole class\n     * hierarchy. If the method is not found an {@link IllegalArgumentException}\n     * is thrown.\n     *\n     * @param type           The type of the class where the method is located.\n     * @param methodName     The method names.\n     * @param parameterTypes All parameter types of the method (may be {@code null}).\n     * @return A .\n     */\n    public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) {\n        Class<?> thisType = type;\n        if (parameterTypes == null) {\n            parameterTypes = new Class<?>[0];\n        }\n        while (thisType != null) {\n            Method[] methodsToTraverse = null;\n            if (thisType.isInterface()) {\n                // Interfaces only contain public (and abstract) methods, no\n                // need to traverse the hierarchy.\n                methodsToTraverse = getAllPublicMethods(thisType);\n            } else {\n                methodsToTraverse = thisType.getDeclaredMethods();\n            }\n            for (Method method : methodsToTraverse) {\n                if (methodName.equals(method.getName())\n                            && checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) {\n                    method.setAccessible(true);\n                    return method;\n                }\n            }\n            thisType = thisType.getSuperclass();\n        }\n\n        throwExceptionIfMethodWasNotFound(type, methodName, null, new Object[]{parameterTypes});\n        return null;\n    }\n\n    /**\n     * Convenience method to get a field from a class type.\n     *\n     * The method will first try to look for a declared field in the same class.\n     * If the method is not declared in this class it will look for the field in\n     * the super class. This will continue throughout the whole class hierarchy.\n     * If the field is not found an {@link IllegalArgumentException} is thrown.\n     *\n     * @param type      The type of the class where the method is located.\n     * @param fieldName The method names.\n     * @return A .\n     */\n    @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n    public static Field getField(Class<?> type, String fieldName) {\n        LinkedList<Class<?>> examine = new LinkedList<Class<?>>();\n        examine.add(type);\n        Set<Class<?>> done = new HashSet<Class<?>>();\n        while (!examine.isEmpty()) {\n            Class<?> thisType = examine.removeFirst();\n            done.add(thisType);\n            final Field[] declaredField = thisType.getDeclaredFields();\n            for (Field field : declaredField) {\n                if (fieldName.equals(field.getName())) {\n                    field.setAccessible(true);\n                    return field;\n                }\n            }\n            Set<Class<?>> potential = new HashSet<Class<?>>();\n            final Class<?> clazz = thisType.getSuperclass();\n            if (clazz != null) {\n                potential.add(thisType.getSuperclass());\n            }\n            potential.addAll((Collection) Arrays.asList(thisType.getInterfaces()));\n            potential.removeAll(done);\n            examine.addAll(potential);\n        }\n\n        throwExceptionIfFieldWasNotFound(type, fieldName, null);\n        return null;\n    }\n\n    /**\n     * Create a new instance of a class without invoking its constructor.\n     *\n     * No byte-code manipulation is needed to perform this operation and thus\n     * it's not necessary use the {@code PowerMockRunner} or\n     * {@code PrepareForTest} annotation to use this functionality.\n     *\n     * @param <T>                The type of the instance to create.\n     * @param classToInstantiate The type of the instance to create.\n     * @return A new instance of type T, created without invoking the\n     * constructor.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> T newInstance(Class<T> classToInstantiate) {\n        int modifiers = classToInstantiate.getModifiers();\n\n        final Object object;\n        if (Modifier.isInterface(modifiers)) {\n            object = Proxy.newProxyInstance(WhiteboxImpl.class.getClassLoader(), new Class<?>[]{classToInstantiate},\n                    new InvocationHandler() {\n                        @Override\n                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n                            return TypeUtils.getDefaultValue(method.getReturnType());\n                        }\n                    });\n        } else if (classToInstantiate.isArray()) {\n            object = Array.newInstance(classToInstantiate.getComponentType(), 0);\n        } else if (Modifier.isAbstract(modifiers)) {\n            throw new IllegalArgumentException(\n                                                      \"Cannot instantiate an abstract class. Please use the ConcreteClassGenerator in PowerMock support to generate a concrete class first.\");\n        } else {\n            Objenesis objenesis = new ObjenesisStd();\n            ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(classToInstantiate);\n            object = thingyInstantiator.newInstance();\n        }\n        return (T) object;\n    }\n\n    /**\n     * Convenience method to get a (declared) constructor from a class type\n     * without having to catch the checked exceptions otherwise required. These\n     * exceptions are wrapped as runtime exceptions. The constructor is also set\n     * to accessible.\n     *\n     * @param type           The type of the class where the constructor is located.\n     * @param parameterTypes All parameter types of the constructor (may be\n     *                       {@code null}).\n     * @return A .\n     */\n    public static Constructor<?> getConstructor(Class<?> type, Class<?>... parameterTypes) {\n        Class<?> unmockedType = WhiteboxImpl.getOriginalUnmockedType(type);\n        try {\n            final Constructor<?> constructor = unmockedType.getDeclaredConstructor(parameterTypes);\n            constructor.setAccessible(true);\n            return constructor;\n        } catch (RuntimeException e) {\n            throw e;\n        } catch (Error e) {\n            throw e;\n        } catch (Throwable e) {\n            throw new ConstructorNotFoundException(String.format(\n                    \"Failed to lookup constructor with parameter types [ %s ] in class %s.\",\n                    getArgumentTypesAsString((Object[]) parameterTypes), unmockedType.getName()), e);\n        }\n    }\n\n    /**\n     * Set the value of a field using reflection. This method will traverse the\n     * super class hierarchy until a field with name <tt>fieldName</tt> is\n     * found.\n     *\n     * @param object    the object whose field to modify\n     * @param fieldName the name of the field\n     * @param value     the new value of the field\n     */\n    public static void setInternalState(Object object, String fieldName, Object value) {\n        Field foundField = findFieldInHierarchy(object, fieldName);\n        setField(object, value, foundField);\n    }\n\n    /**\n     * Set the value of a field using reflection. This method will traverse the\n     * super class hierarchy until a field with name <tt>fieldName</tt> is\n     * found.\n     *\n     * @param object    the object to modify\n     * @param fieldName the name of the field\n     * @param value     the new value of the field\n     */\n    public static void setInternalState(Object object, String fieldName, Object[] value) {\n        setInternalState(object, fieldName, (Object) value);\n    }\n\n    /**\n     * Set the value of a field using reflection. This method will traverse the\n     * super class hierarchy until the first field of type <tt>fieldType</tt> is\n     * found. The <tt>value</tt> will then be assigned to this field.\n     *\n     * @param object    the object to modify\n     * @param fieldType the type of the field\n     * @param value     the new value of the field\n     */\n    public static void setInternalState(Object object, Class<?> fieldType, Object value) {\n        setField(object, value, findFieldInHierarchy(object, new AssignableFromFieldTypeMatcherStrategy(fieldType)));\n    }\n\n    /**\n     * Set the value of a field using reflection. This method will traverse the\n     * super class hierarchy until the first field assignable to the\n     * <tt>value</tt> type is found. The <tt>value</tt> (or\n     * <tt>additionaValues</tt> if present) will then be assigned to this field.\n     *\n     * @param object           the object to modify\n     * @param value            the new value of the field\n     * @param additionalValues Additional values to set on the object\n     */\n    public static void setInternalState(Object object, Object value, Object... additionalValues) {\n        setField(object, value,\n                findFieldInHierarchy(object, new AssignableFromFieldTypeMatcherStrategy(getType(value))));\n        if (additionalValues != null && additionalValues.length > 0) {\n            for (Object additionalValue : additionalValues) {\n                setField(\n                        object,\n                        additionalValue,\n                        findFieldInHierarchy(object, new AssignableFromFieldTypeMatcherStrategy(\n                                                                                                       getType(additionalValue))));\n            }\n        }\n    }\n\n    /**\n     * Set the value of a field using reflection at at specific place in the\n     * class hierarchy (<tt>where</tt>). This first field assignable to\n     * <tt>object</tt> will then be set to <tt>value</tt>.\n     *\n     * @param object the object to modify\n     * @param value  the new value of the field\n     * @param where  the class in the hierarchy where the field is defined\n     */\n    public static void setInternalState(Object object, Object value, Class<?> where) {\n        setField(object, value, findField(object, new AssignableFromFieldTypeMatcherStrategy(getType(value)), where));\n    }\n\n    /**\n     * Set the value of a field using reflection at a specific location (\n     * <tt>where</tt>) in the class hierarchy. The <tt>value</tt> will then be\n     * assigned to this field.\n     *\n     * @param object    the object to modify\n     * @param fieldType the type of the field the should be set.\n     * @param value     the new value of the field\n     * @param where     which class in the hierarchy defining the field\n     */\n    public static void setInternalState(Object object, Class<?> fieldType, Object value, Class<?> where) {\n        if (fieldType == null || where == null) {\n            throw new IllegalArgumentException(\"fieldType and where cannot be null\");\n        }\n\n        setField(object, value, findFieldOrThrowException(fieldType, where));\n    }\n\n    /**\n     * Set the value of a field using reflection. Use this method when you need\n     * to specify in which class the field is declared. This is useful if you\n     * have two fields in a class hierarchy that has the same name but you like\n     * to modify the latter.\n     *\n     * @param object    the object to modify\n     * @param fieldName the name of the field\n     * @param value     the new value of the field\n     * @param where     which class the field is defined\n     */\n    public static void setInternalState(Object object, String fieldName, Object value, Class<?> where) {\n        if (object == null || fieldName == null || fieldName.equals(\"\") || fieldName.startsWith(\" \")) {\n            throw new IllegalArgumentException(\"object, field name, and \\\"where\\\" must not be empty or null.\");\n        }\n\n        final Field field = getField(fieldName, where);\n        try {\n            field.set(object, value);\n        } catch (Exception e) {\n            throw new RuntimeException(\"Internal Error: Failed to set field in method setInternalState.\", e);\n        }\n    }\n\n    /**\n     * Get the value of a field using reflection. This method will iterate\n     * through the entire class hierarchy and return the value of the first\n     * field named <tt>fieldName</tt>. If you want to get a specific field value\n     * at specific place in the class hierarchy please refer to\n     *\n     * @param <T>       the generic type\n     * @param object    the object to modify\n     * @param fieldName the name of the field\n     * @return the internal state\n     * {@link #getInternalState(Object, String, Class)}.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> T getInternalState(Object object, String fieldName) {\n        Field foundField = findFieldInHierarchy(object, fieldName);\n        try {\n            return (T) foundField.get(object);\n        } catch (IllegalAccessException e) {\n            throw new RuntimeException(\"Internal error: Failed to get field in method getInternalState.\", e);\n        }\n    }\n\n    /**\n     * Find field in hierarchy.\n     *\n     * @param object    the object\n     * @param fieldName the field name\n     * @return the field\n     */\n    private static Field findFieldInHierarchy(Object object, String fieldName) {\n        return findFieldInHierarchy(object, new FieldNameMatcherStrategy(fieldName));\n    }\n\n    /**\n     * Find field in hierarchy.\n     *\n     * @param object   the object\n     * @param strategy the strategy\n     * @return the field\n     */\n    private static Field findFieldInHierarchy(Object object, FieldMatcherStrategy strategy) {\n        assertObjectInGetInternalStateIsNotNull(object);\n        return findSingleFieldUsingStrategy(strategy, object, true, getType(object));\n    }\n\n    /**\n     * Find field.\n     *\n     * @param object   the object\n     * @param strategy the strategy\n     * @param where    the where\n     * @return the field\n     */\n    private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) {\n        return findSingleFieldUsingStrategy(strategy, object, false, where);\n    }\n\n    /**\n     * Find single field using strategy.\n     *\n     * @param strategy       the strategy\n     * @param object         the object\n     * @param checkHierarchy the check hierarchy\n     * @param startClass     the start class\n     * @return the field\n     */\n    private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object,\n                                                      boolean checkHierarchy, Class<?> startClass) {\n        assertObjectInGetInternalStateIsNotNull(object);\n        Field foundField = null;\n        final Class<?> originalStartClass = startClass;\n        while (startClass != null) {\n            final Field[] declaredFields = startClass.getDeclaredFields();\n            for (Field field : declaredFields) {\n                if (strategy.matches(field) && hasFieldProperModifier(object, field, false)) {\n                    if (foundField != null) {\n                        throw new TooManyFieldsFoundException(\"Two or more fields matching \" + strategy + \".\");\n                    }\n                    foundField = field;\n                }\n            }\n            if (foundField != null) {\n                break;\n            } else if (!checkHierarchy) {\n                break;\n            }\n            startClass = startClass.getSuperclass();\n        }\n        if (foundField == null) {\n            strategy.notFound(originalStartClass, !isClass(object));\n        }\n        foundField.setAccessible(true);\n        return foundField;\n    }\n\n    /**\n     * Find all fields using strategy.\n     *\n     * @param strategy           the strategy\n     * @param object             the object\n     * @param checkHierarchy     the check hierarchy\n     * @param onlyInstanceFields whether to only allow instance fields\n     * @param startClass         the start class\n     * @return the set\n     */\n    private static Set<Field> findAllFieldsUsingStrategy(FieldMatcherStrategy strategy, Object object,\n                                                         boolean checkHierarchy, boolean onlyInstanceFields,\n                                                         Class<?> startClass) {\n        assertObjectInGetInternalStateIsNotNull(object);\n        final Set<Field> foundFields = new LinkedHashSet<Field>();\n        while (startClass != null) {\n            final Field[] declaredFields = startClass.getDeclaredFields();\n            for (Field field : declaredFields) {\n                if (strategy.matches(field) && hasFieldProperModifier(object, field, onlyInstanceFields)) {\n                    // TODO replace by the class\n                    try {\n                        field.setAccessible(true);\n                        foundFields.add(field);\n                    } catch (Exception ignored) {\n                        // the InaccessibleObjectException is thrown in Java 9 in case\n                        // if a field is private and a module is not open\n                    }\n                }\n            }\n            if (!checkHierarchy) {\n                break;\n            }\n            startClass = startClass.getSuperclass();\n        }\n\n        return Collections.unmodifiableSet(foundFields);\n    }\n\n    /**\n     * Checks for field proper modifier.\n     *\n     * @param object             the object\n     * @param field              the field\n     * @param onlyInstanceFields whether to only allow instance fields\n     * @return true, if successful\n     */\n    private static boolean hasFieldProperModifier(Object object, Field field, boolean onlyInstanceFields) {\n        if (onlyInstanceFields) {\n            return !Modifier.isStatic(field.getModifiers());\n        } else if (object instanceof Class<?>) {\n            return Modifier.isStatic(field.getModifiers());\n        } else {\n            return !Modifier.isStatic(field.getModifiers());\n        }\n    }\n\n    /**\n     * Get the value of a field using reflection. This method will traverse the\n     * super class hierarchy until the first field of type <tt>fieldType</tt> is\n     * found. The value of this field will be returned.\n     *\n     * @param <T>       the generic type\n     * @param object    the object to modify\n     * @param fieldType the type of the field\n     * @return the internal state\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> T getInternalState(Object object, Class<T> fieldType) {\n        Field foundField = findFieldInHierarchy(object, new AssignableToFieldTypeMatcherStrategy(fieldType));\n        try {\n            return (T) foundField.get(object);\n        } catch (IllegalAccessException e) {\n            throw new RuntimeException(\"Internal error: Failed to get field in method getInternalState.\", e);\n        }\n    }\n\n    /**\n     * Get the value of a field using reflection. Use this method when you need\n     * to specify in which class the field is declared. The first field matching\n     * the <tt>fieldType</tt> in <tt>where</tt> will is the field whose value\n     * will be returned.\n     *\n     * @param <T>       the expected type of the field\n     * @param object    the object to modify\n     * @param fieldType the type of the field\n     * @param where     which class the field is defined\n     * @return the internal state\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> T getInternalState(Object object, Class<T> fieldType, Class<?> where) {\n        if (object == null) {\n            throw new IllegalArgumentException(\"object and type are not allowed to be null\");\n        }\n\n        try {\n            return (T) findFieldOrThrowException(fieldType, where).get(object);\n        } catch (IllegalAccessException e) {\n            throw new RuntimeException(\"Internal error: Failed to get field in method getInternalState.\", e);\n        }\n    }\n\n    /**\n     * Get the value of a field using reflection. Use this method when you need\n     * to specify in which class the field is declared. This might be useful\n     * when you have mocked the instance you are trying to access. Use this\n     * method to avoid casting.\n     *\n     * @param <T>       the expected type of the field\n     * @param object    the object to modify\n     * @param fieldName the name of the field\n     * @param where     which class the field is defined\n     * @return the internal state\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> T getInternalState(Object object, String fieldName, Class<?> where) {\n        if (object == null || fieldName == null || fieldName.equals(\"\") || fieldName.startsWith(\" \")) {\n            throw new IllegalArgumentException(\"object, field name, and \\\"where\\\" must not be empty or null.\");\n        }\n\n        Field field = null;\n        try {\n            field = where.getDeclaredField(fieldName);\n            field.setAccessible(true);\n            return (T) field.get(object);\n        } catch (NoSuchFieldException e) {\n            throw new FieldNotFoundException(\"Field '\" + fieldName + \"' was not found in class \" + where.getName()\n                                                     + \".\");\n        } catch (Exception e) {\n            throw new RuntimeException(\"Internal error: Failed to get field in method getInternalState.\", e);\n        }\n    }\n\n    /**\n     * Invoke a private or inner class method without the need to specify the\n     * method name. This is thus a more refactor friendly version of the\n     *\n     * @param <T>       the generic type\n     * @param tested    the tested\n     * @param arguments the arguments\n     * @return the t\n     * @throws Exception the exception\n     *                   {@link #invokeMethod(Object, String, Object...)} method and\n     *                   is recommend over this method for that reason. This method\n     *                   might be useful to test private methods.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Object tested, Object... arguments) throws Exception {\n        return (T) doInvokeMethod(tested, null, null, arguments);\n    }\n\n    /**\n     * Invoke a private or inner class method without the need to specify the\n     * method name. This is thus a more refactor friendly version of the\n     *\n     * @param <T>       the generic type\n     * @param tested    the tested\n     * @param arguments the arguments\n     * @return the t\n     * @throws Exception the exception\n     *                   {@link #invokeMethod(Object, String, Object...)} method and\n     *                   is recommend over this method for that reason. This method\n     *                   might be useful to test private methods.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Class<?> tested, Object... arguments) throws Exception {\n        return (T) doInvokeMethod(tested, null, null, arguments);\n    }\n\n    /**\n     * Invoke a private or inner class method. This might be useful to test\n     * private methods.\n     *\n     * @param <T>             the generic type\n     * @param tested          the tested\n     * @param methodToExecute the method to execute\n     * @param arguments       the arguments\n     * @return the t\n     * @throws Exception the exception\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Object tested, String methodToExecute, Object... arguments)\n            throws Exception {\n        return (T) doInvokeMethod(tested, null, methodToExecute, arguments);\n    }\n\n    /**\n     * Invoke a private or inner class method in cases where power mock cannot\n     * automatically determine the type of the parameters, for example when\n     * mixing primitive types and wrapper types in the same method. For most\n     * situations use {@link #invokeMethod(Class, String, Object...)} instead.\n     *\n     * @param <T>             the generic type\n     * @param tested          the tested\n     * @param methodToExecute the method to execute\n     * @param argumentTypes   the argument types\n     * @param arguments       the arguments\n     * @return the t\n     * @throws Exception Exception that may occur when invoking this method.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Object tested, String methodToExecute, Class<?>[] argumentTypes,\n                                                  Object... arguments) throws Exception {\n        final Class<?> unmockedType = getType(tested);\n        Method method = getMethod(unmockedType, methodToExecute, argumentTypes);\n        if (method == null) {\n            throwExceptionIfMethodWasNotFound(unmockedType, methodToExecute, null, arguments);\n        }\n        return (T) performMethodInvocation(tested, method, arguments);\n    }\n\n    /**\n     * Invoke a private or inner class method in a subclass (defined by\n     * {@code definedIn}) in cases where power mock cannot automatically\n     * determine the type of the parameters, for example when mixing primitive\n     * types and wrapper types in the same method. For most situations use\n     *\n     * @param <T>             the generic type\n     * @param tested          the tested\n     * @param methodToExecute the method to execute\n     * @param definedIn       the defined in\n     * @param argumentTypes   the argument types\n     * @param arguments       the arguments\n     * @return the t\n     * @throws Exception Exception that may occur when invoking this method.\n     *                   {@link #invokeMethod(Class, String, Object...)} instead.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Object tested, String methodToExecute, Class<?> definedIn,\n                                                  Class<?>[] argumentTypes, Object... arguments) throws Exception {\n        Method method = getMethod(definedIn, methodToExecute, argumentTypes);\n        if (method == null) {\n            throwExceptionIfMethodWasNotFound(definedIn, methodToExecute, null, arguments);\n        }\n        return (T) performMethodInvocation(tested, method, arguments);\n    }\n\n    /**\n     * Invoke a private or inner class method in that is located in a subclass\n     * of the tested instance. This might be useful to test private methods.\n     *\n     * @param <T>             the generic type\n     * @param tested          the tested\n     * @param declaringClass  the declaring class\n     * @param methodToExecute the method to execute\n     * @param arguments       the arguments\n     * @return the t\n     * @throws Exception Exception that may occur when invoking this method.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Object tested, Class<?> declaringClass, String methodToExecute,\n                                                  Object... arguments) throws Exception {\n        return (T) doInvokeMethod(tested, declaringClass, methodToExecute, arguments);\n    }\n\n    /**\n     * Invoke a private method in that is located in a subclass of an instance.\n     * This might be useful to test overloaded private methods.\n     *\n     * Use this for overloaded methods only, if possible use\n     *\n     * @param <T>             the generic type\n     * @param object          the object\n     * @param declaringClass  the declaring class\n     * @param methodToExecute the method to execute\n     * @param parameterTypes  the parameter types\n     * @param arguments       the arguments\n     * @return the t\n     * @throws Exception Exception that may occur when invoking this method.\n     *                   {@link #invokeMethod(Object, Object...)} or\n     *                   {@link #invokeMethod(Object, String, Object...)} instead.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Object object, Class<?> declaringClass, String methodToExecute,\n                                                  Class<?>[] parameterTypes, Object... arguments) throws Exception {\n        if (object == null) {\n            throw new IllegalArgumentException(\"object cannot be null\");\n        }\n\n        final Method methodToInvoke = getMethod(declaringClass, methodToExecute, parameterTypes);\n        // Invoke method\n        return (T) performMethodInvocation(object, methodToInvoke, arguments);\n    }\n\n    /**\n     * Invoke a private or inner class method. This might be useful to test\n     * private methods.\n     *\n     * @param <T>             the generic type\n     * @param clazz           the clazz\n     * @param methodToExecute the method to execute\n     * @param arguments       the arguments\n     * @return the t\n     * @throws Exception the exception\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static synchronized <T> T invokeMethod(Class<?> clazz, String methodToExecute, Object... arguments)\n            throws Exception {\n        return (T) doInvokeMethod(clazz, null, methodToExecute, arguments);\n    }\n\n    /**\n     * Do invoke method.\n     *\n     * @param <T>             the generic type\n     * @param tested          the tested\n     * @param declaringClass  the declaring class\n     * @param methodToExecute the method to execute\n     * @param arguments       the arguments\n     * @return the t\n     * @throws Exception the exception\n     */\n    @SuppressWarnings(\"unchecked\")\n    private static <T> T doInvokeMethod(Object tested, Class<?> declaringClass, String methodToExecute,\n                                        Object... arguments) throws Exception {\n        Method methodToInvoke = findMethodOrThrowException(tested, declaringClass, methodToExecute, arguments);\n\n        // Invoke test\n        return (T) performMethodInvocation(tested, methodToInvoke, arguments);\n    }\n\n    /**\n     * Finds and returns a certain method. If the method couldn't be found this\n     * method delegates to\n     *\n     * @param tested          The instance or class containing the method.\n     * @param declaringClass  The class where the method is supposed to be declared (may be\n     *                        {@code null}).\n     * @param methodToExecute The method name. If {@code null} then method will be\n     *                        looked up based on the argument types only.\n     * @param arguments       The arguments of the methods.\n     * @return A single method.\n     * @throws MethodNotFoundException if no method was found.\n     * @throws TooManyMethodsFoundException if too methods matched.\n     * @throws IllegalArgumentException if {@code tested} is null.\n     */\n    public static Method findMethodOrThrowException(Object tested, Class<?> declaringClass, String methodToExecute,\n                                                    Object[] arguments){\n        if (tested == null) {\n            throw new IllegalArgumentException(\"The object to perform the operation on cannot be null.\");\n        }\n\n        /*\n           * Get methods from the type if it's not mocked or from the super type\n           * if the tested object is mocked.\n           */\n        Class<?> testedType = null;\n        if (isClass(tested)) {\n            testedType = (Class<?>) tested;\n        } else {\n            testedType = tested.getClass();\n        }\n\n        Method[] methods = null;\n        if (declaringClass == null) {\n            methods = getAllMethods(testedType);\n        } else {\n            methods = declaringClass.getDeclaredMethods();\n        }\n        Method potentialMethodToInvoke = null;\n        for (Method method : methods) {\n            if (methodToExecute == null || method.getName().equals(methodToExecute)) {\n                Class<?>[] paramTypes = method.getParameterTypes();\n                if ((arguments != null && (paramTypes.length == arguments.length))) {\n                    if (paramTypes.length == 0) {\n                        potentialMethodToInvoke = method;\n                        break;\n                    }\n                    boolean methodFound = checkArgumentTypesMatchParameterTypes(method.isVarArgs(), paramTypes, arguments);\n                    if (methodFound) {\n                        if (potentialMethodToInvoke == null) {\n                            potentialMethodToInvoke = method;\n                        } else if (potentialMethodToInvoke.getName().equals(method.getName())) {\n                            if (areAllArgumentsOfSameType(arguments) && potentialMethodToInvoke.getDeclaringClass() != method.getDeclaringClass()) {\n                                //  We've already found the method which means that \"potentialMethodToInvoke\" overrides \"method\".\n                                return potentialMethodToInvoke;\n                            } else {\n                                // We've found an overloaded method\n                                return getBestMethodCandidate(getType(tested), method.getName(), getTypes(arguments), false);\n                            }\n                        } else {\n                            // A special case to be backward compatible\n                            Method bestCandidateMethod = getMethodWithMostSpecificParameterTypes(method, potentialMethodToInvoke);\n                            if (bestCandidateMethod != null) {\n                                potentialMethodToInvoke = bestCandidateMethod;\n                                continue;\n                            }\n                            /*\n                            * We've already found a method match before, this\n                            * means that PowerMock cannot determine which\n                            * method to expect since there are two methods with\n                            * the same name and the same number of arguments\n                            * but one is using wrapper types.\n                            */\n                            throwExceptionWhenMultipleMethodMatchesFound(\"argument parameter types\", new Method[]{\n                                    potentialMethodToInvoke, method});\n                        }\n                    }\n                } else if (isPotentialVarArgsMethod(method, arguments)) {\n                    if (potentialMethodToInvoke == null) {\n                        potentialMethodToInvoke = method;\n                    } else {\n                        /*\n                               * We've already found a method match before, this means\n                               * that PowerMock cannot determine which method to\n                               * expect since there are two methods with the same name\n                               * and the same number of arguments but one is using\n                               * wrapper types.\n                               */\n                        throwExceptionWhenMultipleMethodMatchesFound(\"argument parameter types\", new Method[]{\n                                potentialMethodToInvoke, method});\n                    }\n                    break;\n                } else if (arguments != null && (paramTypes.length != arguments.length)) {\n                    continue;\n                } else if (arguments == null && paramTypes.length == 1 && !paramTypes[0].isPrimitive()) {\n                    potentialMethodToInvoke = method;\n                }\n            }\n        }\n\n        WhiteboxImpl.throwExceptionIfMethodWasNotFound(getType(tested), methodToExecute, potentialMethodToInvoke,\n                arguments);\n        return potentialMethodToInvoke;\n    }\n\n    /**\n     * Find the method whose parameter types most closely matches the {@code types}.\n     *\n     * @param firstMethodCandidate  The first method candidate\n     * @param secondMethodCandidate The second method candidate\n     * @return The method that most closely matches the provided types or {@code null} if no method match.\n     */\n    private static Method getMethodWithMostSpecificParameterTypes(Method firstMethodCandidate, Method secondMethodCandidate) {\n        Class<?>[] firstMethodCandidateParameterTypes = firstMethodCandidate.getParameterTypes();\n        Class<?>[] secondMethodCandidateParameterTypes = secondMethodCandidate.getParameterTypes();\n\n        Method bestMatch = null;\n        for (int i = 0; i < firstMethodCandidateParameterTypes.length; i++) {\n            Class<?> candidateType1 = toBoxedIfPrimitive(firstMethodCandidateParameterTypes[i]);\n            Class<?> candidateType2 = toBoxedIfPrimitive(secondMethodCandidateParameterTypes[i]);\n\n            if (!candidateType1.equals(candidateType2)) {\n                Method potentialMatch = null;\n                if (candidateType1.isAssignableFrom(candidateType2)) {\n                    potentialMatch = secondMethodCandidate;\n                } else if (candidateType2.isAssignableFrom(candidateType1)) {\n                    potentialMatch = firstMethodCandidate;\n                }\n\n                if (potentialMatch != null) {\n                    if (bestMatch != null && !potentialMatch.equals(bestMatch)) {\n                        /*\n                         * We cannot determine which method is the most specific because one parameter of the first candidate\n                         * was more specific and another parameter of the second candidate was more specific.\n                         */\n                        return null;\n                    } else {\n                        bestMatch = potentialMatch;\n                    }\n                }\n            }\n        }\n\n        return bestMatch;\n    }\n\n    private static Class<?> toBoxedIfPrimitive(Class<?> type) {\n        return type.isPrimitive() ? BoxedWrapper.getBoxedFromPrimitiveType(type) : type;\n    }\n\n    /**\n     * Gets the types.\n     *\n     * @param arguments the arguments\n     * @return the types\n     */\n    private static Class<?>[] getTypes(Object[] arguments) {\n        Class<?>[] classes = new Class<?>[arguments.length];\n        for (int i = 0; i < arguments.length; i++) {\n            classes[i] = getType(arguments[i]);\n        }\n        return classes;\n    }\n\n    /**\n     * Gets the best method candidate.\n     *\n     * @param cls                     the cls\n     * @param methodName              the method name\n     * @param signature               the signature\n     * @param exactParameterTypeMatch {@code true} if the {@code expectedTypes} must match\n     *                                the parameter types must match exactly, {@code false} if\n     *                                the {@code expectedTypes} are allowed to be converted\n     *                                into primitive types if they are of a wrapped type and still\n     *                                match.\n     * @return the best method candidate\n     */\n    public static Method getBestMethodCandidate(Class<?> cls, String methodName, Class<?>[] signature,\n                                                boolean exactParameterTypeMatch) {\n        final Method foundMethod;\n        final Method[] methods = getMethods(cls, methodName, signature, exactParameterTypeMatch);\n        if (methods.length == 1) {\n            foundMethod = methods[0];\n        } else {\n            // We've found overloaded methods, we need to find the best one to invoke.\n            Arrays.sort(methods, ComparatorFactory.createMethodComparator());\n            foundMethod = methods[0];\n        }\n        return foundMethod;\n    }\n\n    /**\n     * Finds and returns the default constructor. If the constructor couldn't be\n     * found this method delegates to {@link #throwExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[])}.\n     *\n     * @param type The type where the constructor should be located.\n     * @return The found constructor.\n     * @throws ConstructorNotFoundException if too many constructors was found.\n     */\n    public static Constructor<?> findDefaultConstructorOrThrowException(Class<?> type) throws\n            ConstructorNotFoundException {\n        if (type == null) {\n            throw new IllegalArgumentException(\"type cannot be null\");\n        }\n\n        final Constructor<?> declaredConstructor;\n        try {\n            declaredConstructor = type.getDeclaredConstructor();\n        } catch (NoSuchMethodException e) {\n            throw new ConstructorNotFoundException(String.format(\"Couldn't find a default constructor in %s.\", type.getName()));\n        }\n        return declaredConstructor;\n    }\n\n    /**\n     * Finds and returns any constructor. If the constructor couldn't be\n     * found this method delegates to {@link #throwExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[])}.\n     *\n     * @param type The type where the constructor should be located.\n     * @return The found constructor.\n     * @throws TooManyConstructorsFoundException if too many constructors was found.\n     */\n    public static Constructor<?> findConstructorOrThrowException(Class<?> type) {\n        final Constructor<?>[] declaredConstructors = filterPowerMockConstructor(type.getDeclaredConstructors());\n        if (declaredConstructors.length > 1) {\n            throwExceptionWhenMultipleConstructorMatchesFound(declaredConstructors);\n        }\n        return declaredConstructors[0];\n    }\n\n    /**\n     * Filter power mock constructor.\n     *\n     * @param declaredConstructors the declared constructors\n     * @return the constructor[]\n     */\n    static Constructor<?>[] filterPowerMockConstructor(Constructor<?>[] declaredConstructors) {\n        Set<Constructor<?>> constructors = new HashSet<Constructor<?>>();\n        for (Constructor<?> constructor : declaredConstructors) {\n            final Class<?>[] parameterTypes = constructor.getParameterTypes();\n            if (parameterTypes.length >= 1\n                        && parameterTypes[parameterTypes.length - 1].getName().equals(\n                    \"org.powermock.core.IndicateReloadClass\")) {\n                continue;\n            } else {\n                constructors.add(constructor);\n            }\n        }\n        return constructors.toArray(new Constructor<?>[constructors.size()]);\n    }\n\n    /**\n     * Finds and returns a certain constructor. If the constructor couldn't be\n     * found this method delegates to\n     *\n     * @param type      The type where the constructor should be located.\n     * @param arguments The arguments passed to the constructor.\n     * @return The found constructor.\n     * @throws ConstructorNotFoundException if no constructor was found.\n     * @throws TooManyConstructorsFoundException if too constructors matched.\n     * @throws IllegalArgumentException if {@code type} is null.\n     */\n    public static Constructor<?> findUniqueConstructorOrThrowException(Class<?> type, Object... arguments) {\n        return new ConstructorFinder(type, arguments).findConstructor();\n    }\n\n    /**\n     * Convert argument types to primitive.\n     *\n     * @param paramTypes the param types\n     * @param arguments  the arguments\n     * @return the class[]\n     */\n    private static Class<?>[] convertArgumentTypesToPrimitive(Class<?>[] paramTypes, Object[] arguments) {\n        Class<?>[] types = new Class<?>[arguments.length];\n        for (int i = 0; i < arguments.length; i++) {\n            Class<?> argumentType = null;\n            if (arguments[i] == null) {\n                argumentType = paramTypes[i];\n            } else {\n                argumentType = getType(arguments[i]);\n            }\n            Class<?> primitiveWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(argumentType);\n            if (primitiveWrapperType == null) {\n                types[i] = argumentType;\n            } else {\n                types[i] = primitiveWrapperType;\n            }\n        }\n        return types;\n    }\n\n    /**\n     * Throw exception if method was not found.\n     *\n     * @param type         the type\n     * @param methodName   the method name\n     * @param methodToMock the method to mock\n     * @param arguments    the arguments\n     */\n    public static void throwExceptionIfMethodWasNotFound(Class<?> type, String methodName, Method methodToMock,\n                                                         Object... arguments) {\n        if (methodToMock == null) {\n            String methodNameData = \"\";\n            if (methodName != null) {\n                methodNameData = \"with name '\" + methodName + \"' \";\n            }\n            throw new MethodNotFoundException(\"No method found \" + methodNameData + \"with parameter types: [ \"\n                                                      + getArgumentTypesAsString(arguments) + \" ] in class \" + getOriginalUnmockedType(type)\n                                                                                                                       .getName() + \".\");\n        }\n    }\n\n    /**\n     * Throw exception if field was not found.\n     *\n     * @param type      the type\n     * @param fieldName the field name\n     * @param field     the field\n     */\n    public static void throwExceptionIfFieldWasNotFound(Class<?> type, String fieldName, Field field) {\n        if (field == null) {\n            throw new FieldNotFoundException(\"No field was found with name '\" + fieldName + \"' in class \"\n                                                     + getOriginalUnmockedType(type).getName() + \".\");\n        }\n    }\n\n    /**\n     * Throw exception if constructor was not found.\n     *\n     * @param type                 the type\n     * @param potentialConstructor the potential constructor\n     * @param arguments            the arguments\n     */\n    static void throwExceptionIfConstructorWasNotFound(Class<?> type, Constructor<?> potentialConstructor,\n                                                       Object... arguments) {\n        if (potentialConstructor == null) {\n            String message = \"No constructor found in class '\" + getOriginalUnmockedType(type).getName() + \"' with \"\n                                     + \"parameter types: [ \" + getArgumentTypesAsString(arguments) + \" ].\";\n            throw new ConstructorNotFoundException(message);\n        }\n    }\n\n    /**\n     * Gets the argument types as string.\n     *\n     * @param arguments the arguments\n     * @return the argument types as string\n     */\n    static String getArgumentTypesAsString(Object... arguments) {\n        StringBuilder argumentsAsString = new StringBuilder();\n        final String noParameters = \"<none>\";\n        if (arguments != null && arguments.length != 0) {\n            for (int i = 0; i < arguments.length; i++) {\n                String argumentName = null;\n                Object argument = arguments[i];\n\n                if (argument instanceof Class<?>) {\n                    argumentName = ((Class<?>) argument).getName();\n                } else if (argument instanceof Class<?>[] && arguments.length == 1) {\n                    Class<?>[] argumentArray = (Class<?>[]) argument;\n                    if (argumentArray.length > 0) {\n                        for (int j = 0; j < argumentArray.length; j++) {\n                            appendArgument(argumentsAsString, j,\n                                    argumentArray[j] == null ? \"null\" : getUnproxyType(argumentArray[j]).getName(),\n                                    argumentArray);\n                        }\n                        return argumentsAsString.toString();\n                    } else {\n                        argumentName = noParameters;\n                    }\n                } else if (argument == null) {\n                    argumentName = \"null\";\n                } else {\n                    argumentName = getUnproxyType(argument).getName();\n                }\n                appendArgument(argumentsAsString, i, argumentName, arguments);\n            }\n        } else {\n            argumentsAsString.append(\"<none>\");\n        }\n        return argumentsAsString.toString();\n    }\n\n    /**\n     * Append argument.\n     *\n     * @param argumentsAsString the arguments as string\n     * @param index             the index\n     * @param argumentName      the argument name\n     * @param arguments         the arguments\n     */\n    private static void appendArgument(StringBuilder argumentsAsString, int index, String argumentName,\n                                       Object[] arguments) {\n        argumentsAsString.append(argumentName);\n        if (index != arguments.length - 1) {\n            argumentsAsString.append(\", \");\n        }\n    }\n\n    /**\n     * Invoke a constructor. Useful for testing classes with a private\n     * constructor when PowerMock cannot determine which constructor to invoke.\n     * This only happens if you have two constructors with the same number of\n     * arguments where one is using primitive data types and the other is using\n     * the wrapped counter part. For example:\n     *\n     * <pre>\n     * public class MyClass {\n     * private MyClass(Integer i) {\n     * ...\n     * }\n     *\n     * private MyClass(int i) {\n     * ...\n     * }\n     * </pre>\n     *\n     * This ought to be a really rare case. So for most situation, use\n     *\n     * @param <T>                                   the generic type\n     * @param classThatContainsTheConstructorToTest the class that contains the constructor to test\n     * @param parameterTypes                        the parameter types\n     * @param arguments                             the arguments\n     * @return The object created after the constructor has been invoked.\n     * @throws Exception If an exception occur when invoking the constructor.\n     *                   {@link #invokeConstructor(Class, Object...)} instead.\n     */\n    public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Class<?>[] parameterTypes,\n                                          Object[] arguments) throws Exception {\n        if (parameterTypes != null && arguments != null) {\n            if (parameterTypes.length != arguments.length) {\n                throw new IllegalArgumentException(\"parameterTypes and arguments must have the same length\");\n            }\n        }\n\n        Constructor<T> constructor = null;\n        try {\n            constructor = classThatContainsTheConstructorToTest.getDeclaredConstructor(parameterTypes);\n        } catch (Exception e) {\n            throw new ConstructorNotFoundException(\"Could not lookup the constructor\", e);\n        }\n\n        return createInstance(constructor, arguments);\n    }\n\n    /**\n     * Invoke a constructor. Useful for testing classes with a private\n     * constructor.\n     *\n     * @param <T>                                   the generic type\n     * @param classThatContainsTheConstructorToTest the class that contains the constructor to test\n     * @param arguments                             the arguments\n     * @return The object created after the constructor has been invoked.\n     * @throws Exception If an exception occur when invoking the constructor.\n     */\n    public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Object... arguments)\n            throws Exception {\n\n        if (classThatContainsTheConstructorToTest == null) {\n            throw new IllegalArgumentException(\"The class should contain the constructor cannot be null.\");\n        }\n\n        Class<?>[] argumentTypes = null;\n        if (arguments == null) {\n            argumentTypes = new Class<?>[0];\n        } else {\n            argumentTypes = new Class<?>[arguments.length];\n            for (int i = 0; i < arguments.length; i++) {\n                argumentTypes[i] = getType(arguments[i]);\n            }\n        }\n\n        Constructor<T> constructor = null;\n\n        constructor = getBestCandidateConstructor(classThatContainsTheConstructorToTest, argumentTypes, arguments);\n\n        return createInstance(constructor, arguments);\n    }\n\n    private static <T> Constructor<T> getBestCandidateConstructor(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes, Object[] arguments) {\n        Constructor<T> constructor;\n\n\n        Constructor<T> potentialConstructorWrapped = getPotentialConstructorWrapped(classThatContainsTheConstructorToTest, argumentTypes);\n\n        Constructor<T> potentialConstructorPrimitive = getPotentialConstructorPrimitive(classThatContainsTheConstructorToTest, argumentTypes);\n\n        if (potentialConstructorPrimitive == null && potentialConstructorWrapped == null) {\n            // Check if we can find a matching var args constructor.\n            constructor = getPotentialVarArgsConstructor(classThatContainsTheConstructorToTest, arguments);\n            if (constructor == null) {\n                throw new ConstructorNotFoundException(\"Failed to find a constructor with parameter types: [\"\n                                                               + getArgumentTypesAsString(arguments) + \"]\");\n            }\n        } else if (potentialConstructorPrimitive == null) {\n            constructor = potentialConstructorWrapped;\n        } else if (potentialConstructorWrapped == null) {\n            constructor = potentialConstructorPrimitive;\n        } else if (arguments == null || arguments.length == 0 && potentialConstructorPrimitive != null) {\n            constructor = potentialConstructorPrimitive;\n        } else {\n            throw new TooManyConstructorsFoundException(\n                                                               \"Could not determine which constructor to execute. Please specify the parameter types by hand.\");\n        }\n        return constructor;\n    }\n\n    private static <T> Constructor<T> getPotentialConstructorWrapped(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes) {\n        return new CandidateConstructorSearcher<T>(classThatContainsTheConstructorToTest, argumentTypes)\n                       .findConstructor();\n    }\n\n    private static <T> Constructor<T> getPotentialConstructorPrimitive(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes) {\n\n        Constructor<T> potentialConstructorPrimitive = null;\n        try {\n            Class<?>[] primitiveType = PrimitiveWrapper.toPrimitiveType(argumentTypes);\n\n            if (!argumentTypesEqualsPrimitiveTypes(argumentTypes, primitiveType)) {\n\n                potentialConstructorPrimitive = new CandidateConstructorSearcher<T>(classThatContainsTheConstructorToTest, primitiveType)\n                                                        .findConstructor();\n            }\n        } catch (Exception e) {\n            // Do nothing\n        }\n        return potentialConstructorPrimitive;\n    }\n\n    private static boolean argumentTypesEqualsPrimitiveTypes(Class<?>[] argumentTypes, Class<?>[] primitiveType) {\n        for (int index = 0; index < argumentTypes.length; index++) {\n            if (!argumentTypes[index].equals(primitiveType[index])) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * Gets the potential var args constructor.\n     *\n     * @param <T>                                   the generic type\n     * @param classThatContainsTheConstructorToTest the class that contains the constructor to test\n     * @param arguments                             the arguments\n     * @return the potential var args constructor\n     */\n    @SuppressWarnings(\"unchecked\")\n    private static <T> Constructor<T> getPotentialVarArgsConstructor(Class<T> classThatContainsTheConstructorToTest,\n                                                                     Object... arguments) {\n        Constructor<T>[] declaredConstructors = (Constructor<T>[]) classThatContainsTheConstructorToTest\n                                                                           .getDeclaredConstructors();\n        for (Constructor<T> possibleVarArgsConstructor : declaredConstructors) {\n            if (possibleVarArgsConstructor.isVarArgs()) {\n                if (arguments == null || arguments.length == 0) {\n                    return possibleVarArgsConstructor;\n                } else {\n                    Class<?>[] parameterTypes = possibleVarArgsConstructor.getParameterTypes();\n                    if (parameterTypes[parameterTypes.length - 1].getComponentType().isAssignableFrom(\n                            getType(arguments[0]))) {\n                        return possibleVarArgsConstructor;\n                    }\n                }\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Creates the instance.\n     *\n     * @param <T>         the generic type\n     * @param constructor the constructor\n     * @param arguments   the arguments\n     * @return the t\n     * @throws Exception the exception\n     */\n    private static <T> T createInstance(Constructor<T> constructor, Object... arguments) throws Exception {\n        if (constructor == null) {\n            throw new IllegalArgumentException(\"Constructor cannot be null\");\n        }\n        constructor.setAccessible(true);\n\n        T createdObject = null;\n        try {\n            if (constructor.isVarArgs()) {\n                Class<?>[] parameterTypes = constructor.getParameterTypes();\n                final int varArgsIndex = parameterTypes.length - 1;\n                Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();\n                Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);\n                Object[] completeArgumentList = new Object[parameterTypes.length];\n                System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);\n                completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;\n                createdObject = constructor.newInstance(completeArgumentList);\n            } else {\n                createdObject = constructor.newInstance(arguments);\n            }\n        } catch (InvocationTargetException e) {\n            Throwable cause = e.getCause();\n            if (cause instanceof Exception) {\n                throw (Exception) cause;\n            } else if (cause instanceof Error) {\n                throw (Error) cause;\n            }\n        }\n        return createdObject;\n    }\n\n    /**\n     * Creates the and populate var args array.\n     *\n     * @param varArgsType          the var args type\n     * @param varArgsStartPosition the var args start position\n     * @param arguments            the arguments\n     * @return the object\n     */\n    private static Object createAndPopulateVarArgsArray(Class<?> varArgsType, int varArgsStartPosition,\n                                                        Object... arguments) {\n        Object arrayInstance = Array.newInstance(varArgsType, arguments.length - varArgsStartPosition);\n        for (int i = varArgsStartPosition; i < arguments.length; i++) {\n            Array.set(arrayInstance, i - varArgsStartPosition, arguments[i]);\n        }\n        return arrayInstance;\n    }\n\n    /**\n     * Get all declared constructors in the class and set accessible to\n     * {@code true}.\n     *\n     * @param clazz The class whose constructors to get.\n     * @return All constructors declared in this class hierarchy.\n     */\n    public static Constructor<?>[] getAllConstructors(Class<?> clazz) {\n        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();\n        for (Constructor<?> constructor : declaredConstructors) {\n            if (!constructor.isAccessible()) {\n                constructor.setAccessible(true);\n            }\n        }\n        return declaredConstructors;\n    }\n\n    /**\n     * Get all methods in a class hierarchy! Both declared an non-declared (no\n     * duplicates).\n     *\n     * @param clazz The class whose methods to get.\n     * @return All methods declared in this class hierarchy.\n     */\n    public static Method[] getAllMethods(Class<?> clazz) {\n        Method[] allMethods = allClassMethodsCache.get(clazz);\n        if (allMethods == null) {\n            // Allows a race between concurrent threads coming for clazz's methods at the same time,\n            // but the race seems to be harmless.\n            allMethods = doGetAllMethods(clazz);\n            allClassMethodsCache.put(clazz, allMethods);\n        }\n        return allMethods;\n    }\n\n    private static Method[] doGetAllMethods(Class<?> clazz) {\n        if (clazz == null) {\n            throw new IllegalArgumentException(\"You must specify a class in order to get the methods.\");\n        }\n        Set<Method> methods = new LinkedHashSet<Method>();\n\n        Class<?> thisType = clazz;\n\n        while (thisType != null) {\n            final Class<?> type = thisType;\n            final Method[] declaredMethods = AccessController.doPrivileged(new PrivilegedAction<Method[]>() {\n\n                @Override\n                public Method[] run() {\n                    return type.getDeclaredMethods();\n                }\n\n            });\n            for (Method method : declaredMethods) {\n                if(!\"finalize\".equals(method.getName())) {\n                    method.setAccessible(true);\n                    methods.add(method);\n                }\n            }\n            Collections.addAll(methods, type.getMethods());\n            thisType = thisType.getSuperclass();\n        }\n        return methods.toArray(new Method[methods.size()]);\n    }\n\n    /**\n     * Get all public methods for a class (no duplicates)! Note that the\n     * class-hierarchy will not be traversed.\n     *\n     * @param clazz The class whose methods to get.\n     * @return All public methods declared in class.\n     */\n    private static Method[] getAllPublicMethods(Class<?> clazz) {\n        if (clazz == null) {\n            throw new IllegalArgumentException(\"You must specify a class in order to get the methods.\");\n        }\n        Set<Method> methods = new LinkedHashSet<Method>();\n\n        for (Method method : clazz.getMethods()) {\n            method.setAccessible(true);\n            methods.add(method);\n        }\n        return methods.toArray(new Method[0]);\n    }\n\n    /**\n     * Get all fields in a class hierarchy! Both declared an non-declared (no\n     * duplicates).\n     *\n     * @param clazz The class whose fields to get.\n     * @return All fields declared in this class hierarchy.\n     */\n    public static Field[] getAllFields(Class<?> clazz) {\n        if (clazz == null) {\n            throw new IllegalArgumentException(\"You must specify the class that contains the fields\");\n        }\n        Set<Field> fields = new LinkedHashSet<Field>();\n\n        Class<?> thisType = clazz;\n\n        while (thisType != null) {\n            final Field[] declaredFields = thisType.getDeclaredFields();\n            for (Field field : declaredFields) {\n                field.setAccessible(true);\n                fields.add(field);\n            }\n            thisType = thisType.getSuperclass();\n        }\n        return fields.toArray(new Field[fields.size()]);\n    }\n\n    /**\n     * Get the first parent constructor defined in a super class of\n     * {@code klass}.\n     *\n     * @param klass The class where the constructor is located. {@code null}\n     *              ).\n     * @return A .\n     */\n    public static Constructor<?> getFirstParentConstructor(Class<?> klass) {\n        try {\n            return getOriginalUnmockedType(klass).getSuperclass().getDeclaredConstructors()[0];\n        } catch (Exception e) {\n            throw new ConstructorNotFoundException(\"Failed to lookup constructor.\", e);\n        }\n    }\n\n    /**\n     * Finds and returns a method based on the input parameters. If no\n     * {@code parameterTypes} are present the method will return the first\n     * method with name {@code methodNameToMock}. If no method was found,\n     * {@code null} will be returned. If no {@code methodName} is\n     * specified the method will be found based on the parameter types. If\n     * neither method name nor parameters are specified an\n     *\n     * @param <T>            the generic type\n     * @param type           the type\n     * @param methodName     the method name\n     * @param parameterTypes the parameter types\n     * @return the method {@link IllegalArgumentException} will be thrown.\n     */\n    public static <T> Method findMethod(Class<T> type, String methodName, Class<?>... parameterTypes) {\n        if (methodName == null && parameterTypes == null) {\n            throw new IllegalArgumentException(\"You must specify a method name or parameter types.\");\n        }\n        List<Method> matchingMethodsList = new LinkedList<Method>();\n        for (Method method : getAllMethods(type)) {\n            if (methodName == null || method.getName().equals(methodName)) {\n                if (parameterTypes != null && parameterTypes.length > 0) {\n                    // If argument types was supplied, make sure that they\n                    // match.\n                    Class<?>[] paramTypes = method.getParameterTypes();\n                    if (!checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, paramTypes)) {\n                        continue;\n                    }\n                }\n                // Add the method to the matching methods list.\n                matchingMethodsList.add(method);\n            }\n        }\n\n        Method methodToMock = null;\n        if (matchingMethodsList.size() > 0) {\n            if (matchingMethodsList.size() == 1) {\n                // We've found a unique method match.\n                methodToMock = matchingMethodsList.get(0);\n            } else if ((parameterTypes != null ? parameterTypes.length : 0) == 0) {\n                /*\n                     * If we've found several matches and we've supplied no\n                     * parameter types, go through the list of found methods and see\n                     * if we have a method with no parameters. In that case return\n                     * that method.\n                     */\n                for (Method method : matchingMethodsList) {\n                    if (method.getParameterTypes().length == 0) {\n                        methodToMock = method;\n                        break;\n                    }\n                }\n\n                if (methodToMock == null) {\n                    WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound(\"argument parameter types\",\n                            matchingMethodsList.toArray(new Method[matchingMethodsList.size()]));\n                }\n            } else {\n                // We've found several matching methods.\n                WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound(\"argument parameter types\",\n                        matchingMethodsList.toArray(new Method[matchingMethodsList.size()]));\n            }\n        }\n\n        return methodToMock;\n    }\n\n\n    /**\n     * Gets the unmocked type.\n     *\n     * @param <T>  the generic type\n     * @param type the type\n     * @return the unmocked type\n     */\n    public static <T> Class<?> getOriginalUnmockedType(Class<T> type) {\n        return getUnproxiedType(type).getOriginalType();\n    }\n\n    public static <T> UnproxiedType getUnproxiedType(Class<T> type) {\n        return proxyFrameworks.getUnproxiedType(type);\n    }\n\n    /**\n     * Throw exception when multiple method matches found.\n     *\n     * @param helpInfo the help info\n     * @param methods  the methods\n     */\n    static void throwExceptionWhenMultipleMethodMatchesFound(String helpInfo, Method[] methods) {\n        if (methods == null || methods.length < 2) {\n            throw new IllegalArgumentException(\n                                                      \"Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods.\");\n        }\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"Several matching methods found, please specify the \");\n        sb.append(helpInfo);\n        sb.append(\" so that PowerMock can determine which method you're referring to.\\n\");\n        sb.append(\"Matching methods in class \").append(methods[0].getDeclaringClass().getName()).append(\" were:\\n\");\n\n        for (Method method : methods) {\n            sb.append(method.getReturnType().getName()).append(\" \");\n            sb.append(method.getName()).append(\"( \");\n            final Class<?>[] parameterTypes = method.getParameterTypes();\n            for (Class<?> paramType : parameterTypes) {\n                sb.append(paramType.getName()).append(\".class \");\n            }\n            sb.append(\")\\n\");\n        }\n        throw new TooManyMethodsFoundException(sb.toString());\n    }\n\n    /**\n     * Throw exception when multiple constructor matches found.\n     *\n     * @param constructors the constructors\n     */\n    static void throwExceptionWhenMultipleConstructorMatchesFound(Constructor<?>[] constructors) {\n        if (constructors == null || constructors.length < 2) {\n            throw new IllegalArgumentException(\n                                                      \"Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors.\");\n        }\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\\n\");\n        sb.append(\"Matching constructors in class \").append(constructors[0].getDeclaringClass().getName())\n          .append(\" were:\\n\");\n\n        for (Constructor<?> constructor : constructors) {\n            sb.append(constructor.getName()).append(\"( \");\n            final Class<?>[] parameterTypes = constructor.getParameterTypes();\n            for (Class<?> paramType : parameterTypes) {\n                sb.append(paramType.getName()).append(\".class \");\n            }\n            sb.append(\")\\n\");\n        }\n        throw new TooManyConstructorsFoundException(sb.toString());\n    }\n\n    /**\n     * Find method or throw exception.\n     *\n     * @param type           the type\n     * @param methodName     the method name\n     * @param parameterTypes the parameter types\n     * @return the method\n     */\n    @SuppressWarnings(\"all\")\n    public static Method findMethodOrThrowException(Class<?> type, String methodName, Class<?>... parameterTypes) {\n        Method methodToMock = findMethod(type, methodName, parameterTypes);\n        throwExceptionIfMethodWasNotFound(type, methodName, methodToMock, (Object[]) parameterTypes);\n        return methodToMock;\n    }\n\n    /**\n     * Get an array of {@link Method}'s that matches the supplied list of method\n     * names. Both instance and static methods are taken into account.\n     *\n     * @param clazz       The class that should contain the methods.\n     * @param methodNames Names of the methods that will be returned.\n     * @return An array of Method's.\n     */\n    public static Method[] getMethods(Class<?> clazz, String... methodNames) {\n        if (methodNames == null || methodNames.length == 0) {\n            throw new IllegalArgumentException(\"You must supply at least one method name.\");\n        }\n        final List<Method> methodsToMock = new LinkedList<Method>();\n        Method[] allMethods = null;\n        if (clazz.isInterface()) {\n            allMethods = getAllPublicMethods(clazz);\n        } else {\n            allMethods = getAllMethods(clazz);\n        }\n\n        for (Method method : allMethods) {\n            for (String methodName : methodNames) {\n                if (method.getName().equals(methodName)) {\n                    method.setAccessible(true);\n                    methodsToMock.add(method);\n                }\n            }\n        }\n\n        final Method[] methodArray = methodsToMock.toArray(new Method[0]);\n        if (methodArray.length == 0) {\n            throw new MethodNotFoundException(String.format(\n                    \"No methods matching the name(s) %s were found in the class hierarchy of %s.\",\n                    concatenateStrings(methodNames), getType(clazz)));\n        }\n        return methodArray;\n    }\n\n    /**\n     * Get an array of {@link Method}'s that matches the method name and whose\n     * argument types are assignable from {@code expectedTypes}. Both\n     * instance and static methods are taken into account.\n     *\n     * @param clazz                   The class that should contain the methods.\n     * @param methodName              Names of the methods that will be returned.\n     * @param expectedTypes           The methods must match\n     * @param exactParameterTypeMatch {@code true} if the {@code expectedTypes} must match\n     *                                the parameter types must match exactly, {@code false} if\n     *                                the {@code expectedTypes} are allowed to be converted\n     *                                into primitive types if they are of a wrapped type and still\n     *                                match.\n     * @return An array of Method's.\n     */\n    public static Method[] getMethods(Class<?> clazz, String methodName, Class<?>[] expectedTypes,\n                                      boolean exactParameterTypeMatch) {\n        List<Method> matchingArgumentTypes = new LinkedList<Method>();\n        Method[] methods = getMethods(clazz, methodName);\n        for (Method method : methods) {\n            final Class<?>[] parameterTypes = method.getParameterTypes();\n            if (checkIfParameterTypesAreSame(method.isVarArgs(), expectedTypes, parameterTypes)\n                        || (!exactParameterTypeMatch && checkIfParameterTypesAreSame(method.isVarArgs(),\n                    convertParameterTypesToPrimitive(expectedTypes),\n                    convertParameterTypesToPrimitive(parameterTypes)))) {\n                matchingArgumentTypes.add(method);\n            }\n        }\n        final Method[] methodArray = matchingArgumentTypes.toArray(new Method[0]);\n        if (methodArray.length == 0) {\n            throw new MethodNotFoundException(String.format(\n                    \"No methods matching the name(s) %s were found in the class hierarchy of %s.\",\n                    concatenateStrings(methodName), getType(clazz)));\n        }\n        return matchingArgumentTypes.toArray(new Method[matchingArgumentTypes.size()]);\n    }\n\n    /**\n     * Get an array of {@link Field}'s that matches the supplied list of field\n     * names. Both instance and static fields are taken into account.\n     *\n     * @param clazz      The class that should contain the fields.\n     * @param fieldNames Names of the fields that will be returned.\n     * @return An array of Field's. May be of length 0 but not .\n     */\n    public static Field[] getFields(Class<?> clazz, String... fieldNames) {\n        final List<Field> fields = new LinkedList<Field>();\n\n        for (Field field : getAllFields(clazz)) {\n            for (String fieldName : fieldNames) {\n                if (field.getName().equals(fieldName)) {\n                    fields.add(field);\n                }\n            }\n        }\n\n        final Field[] fieldArray = fields.toArray(new Field[fields.size()]);\n        if (fieldArray.length == 0) {\n            throw new FieldNotFoundException(String.format(\n                    \"No fields matching the name(s) %s were found in the class hierarchy of %s.\",\n                    concatenateStrings(fieldNames), getType(clazz)));\n        }\n        return fieldArray;\n    }\n\n    /**\n     * Perform method invocation.\n     *\n     * @param <T>            the generic type\n     * @param tested         the tested\n     * @param methodToInvoke the method to invoke\n     * @param arguments      the arguments\n     * @return the t\n     * @throws Exception the exception\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> T performMethodInvocation(Object tested, Method methodToInvoke, Object... arguments)\n            throws Exception {\n        final boolean accessible = methodToInvoke.isAccessible();\n        if (!accessible) {\n            methodToInvoke.setAccessible(true);\n        }\n        try {\n            if (isPotentialVarArgsMethod(methodToInvoke, arguments)) {\n                Class<?>[] parameterTypes = methodToInvoke.getParameterTypes();\n                final int varArgsIndex = parameterTypes.length - 1;\n                Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();\n                Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);\n                Object[] completeArgumentList = new Object[parameterTypes.length];\n                System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);\n                completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;\n                return (T) methodToInvoke.invoke(tested, completeArgumentList);\n            } else {\n                return (T) methodToInvoke.invoke(tested, arguments == null ? new Object[]{arguments} : arguments);\n            }\n        } catch (InvocationTargetException e) {\n            Throwable cause = e.getCause();\n            if (cause instanceof Exception) {\n                throw (Exception) cause;\n            } else if (cause instanceof Error) {\n                throw (Error) cause;\n            } else {\n                throw new MethodInvocationException(cause);\n            }\n        } finally {\n            if (!accessible) {\n                methodToInvoke.setAccessible(false);\n            }\n        }\n    }\n\n    /**\n     * Gets the all method except.\n     *\n     * @param <T>         the generic type\n     * @param type        the type\n     * @param methodNames the method names\n     * @return the all method except\n     */\n    public static <T> Method[] getAllMethodExcept(Class<T> type, String... methodNames) {\n        List<Method> methodsToMock = new LinkedList<Method>();\n        Method[] methods = getAllMethods(type);\n        iterateMethods:\n        for (Method method : methods) {\n            for (String methodName : methodNames) {\n                if (method.getName().equals(methodName)) {\n                    continue iterateMethods;\n                }\n            }\n            methodsToMock.add(method);\n        }\n        return methodsToMock.toArray(new Method[0]);\n    }\n\n    /**\n     * Gets the all metods except.\n     *\n     * @param <T>                 the generic type\n     * @param type                the type\n     * @param methodNameToExclude the method name to exclude\n     * @param argumentTypes       the argument types\n     * @return the all metods except\n     */\n    public static <T> Method[] getAllMethodsExcept(Class<T> type, String methodNameToExclude, Class<?>[] argumentTypes) {\n        Method[] methods = getAllMethods(type);\n        List<Method> methodList = new ArrayList<Method>();\n        outer:\n        for (Method method : methods) {\n            if (method.getName().equals(methodNameToExclude)) {\n                if (argumentTypes != null && argumentTypes.length > 0) {\n                    final Class<?>[] args = method.getParameterTypes();\n                    if (args != null && args.length == argumentTypes.length) {\n                        for (int i = 0; i < args.length; i++) {\n                            if (args[i].isAssignableFrom(getOriginalUnmockedType(argumentTypes[i]))) {\n                                /*\n                                         * Method was not found thus it should not be\n                                         * mocked. Continue to investigate the next\n                                         * method.\n                                         */\n                                continue outer;\n                            }\n                        }\n                    }\n                } else {\n                    continue;\n                }\n            }\n            methodList.add(method);\n        }\n        return methodList.toArray(new Method[0]);\n    }\n\n    /**\n     * Are all methods static.\n     *\n     * @param methods the methods\n     * @return true, if successful\n     */\n    public static boolean areAllMethodsStatic(Method... methods) {\n        for (Method method : methods) {\n            if (!Modifier.isStatic(method.getModifiers())) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * Check if all arguments are of the same type.\n     *\n     * @param arguments the arguments\n     * @return true, if successful\n     */\n    static boolean areAllArgumentsOfSameType(Object[] arguments) {\n        if (arguments == null || arguments.length <= 1) {\n            return true;\n        }\n\n        // Handle null values\n        int index = 0;\n        Object object = null;\n        while (object == null && index < arguments.length) {\n            object = arguments[index++];\n        }\n\n        if (object == null) {\n            return true;\n        }\n        // End of handling null values\n\n        final Class<?> firstArgumentType = getType(object);\n        for (int i = index; i < arguments.length; i++) {\n            final Object argument = arguments[i];\n            if (argument != null && !getType(argument).isAssignableFrom(firstArgumentType)) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Check argument types match parameter types.\n     *\n     * @param isVarArgs      If the last parameter is a var args.\n     * @param parameterTypes the parameter types\n     * @param arguments      the arguments\n     * @return if all actual parameter types are assignable from the expected\n     * arguments, otherwise.\n     */\n     static boolean checkArgumentTypesMatchParameterTypes(boolean isVarArgs, Class<?>[] parameterTypes,\n                                                                 Object[] arguments) {\n        if (parameterTypes == null) {\n            throw new IllegalArgumentException(\"parameter types cannot be null\");\n        } else if (!isVarArgs && arguments.length != parameterTypes.length) {\n            return false;\n        }\n        for (int i = 0; i < arguments.length; i++) {\n            Object argument = arguments[i];\n            if (argument == null) {\n                final int index;\n                if (i >= parameterTypes.length) {\n                    index = parameterTypes.length - 1;\n                } else {\n                    index = i;\n                }\n                final Class<?> type = parameterTypes[index];\n                if (type.isPrimitive()) {\n                    // Primitives cannot be null\n                    return false;\n                } else {\n                    continue;\n                }\n            } else if (i >= parameterTypes.length) {\n                if (isAssignableFrom(parameterTypes[parameterTypes.length - 1], getType(argument))) {\n                    continue;\n                } else {\n                    return false;\n                }\n            } else {\n                boolean assignableFrom = isAssignableFrom(parameterTypes[i], getType(argument));\n                final boolean isClass = parameterTypes[i].equals(Class.class) && isClass(argument);\n                if (!assignableFrom && !isClass) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n\n    static boolean isAssignableFrom(Class<?> type, Class<?> from) {\n        boolean assignableFrom;\n        Class<?> theType = getComponentType(type);\n        Class<?> theFrom = getComponentType(from);\n        assignableFrom = theType.isAssignableFrom(theFrom);\n        if (!assignableFrom && PrimitiveWrapper.hasPrimitiveCounterPart(theFrom)) {\n            final Class<?> primitiveFromWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(theFrom);\n            if (primitiveFromWrapperType != null) {\n                assignableFrom = theType.isAssignableFrom(primitiveFromWrapperType);\n            }\n        }\n        return assignableFrom;\n    }\n\n    private static Class<?> getComponentType(Class<?> type) {\n        Class<?> theType = type;\n        while (theType.isArray()) {\n            theType = theType.getComponentType();\n        }\n        return theType;\n    }\n\n    /**\n     * Gets the type.\n     *\n     * @param object the object\n     * @return The type of the of an object.\n     */\n    public static Class<?> getType(Object object) {\n        Class<?> type = null;\n        if (isClass(object)) {\n            type = (Class<?>) object;\n        } else if (object != null) {\n            type = object.getClass();\n        }\n        return type;\n    }\n\n    /**\n     * Gets the type.\n     *\n     * @param object the object\n     * @return The type of the of an object.\n     */\n    public static Class<?> getUnproxyType(Object object) {\n        Class<?> type = null;\n        if (isClass(object)) {\n            type = (Class<?>) object;\n        } else if (object != null) {\n            type = object.getClass();\n        }\n        return type == null ? null : getOriginalUnmockedType(type);\n    }\n\n    /**\n     * Get an inner class type.\n     *\n     * @param declaringClass The class in which the inner class is declared.\n     * @param name           The unqualified name (simple name) of the inner class.\n     * @return The type.\n     * @throws ClassNotFoundException the class not found exception\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static Class<Object> getInnerClassType(Class<?> declaringClass, String name) throws ClassNotFoundException {\n        return (Class<Object>) Class.forName(declaringClass.getName() + \"$\" + name);\n    }\n\n    /**\n     * Get the type of a local inner class.\n     *\n     * @param declaringClass The class in which the local inner class is declared.\n     * @param occurrence     The occurrence of the local class. For example if you have two\n     *                       local classes in the {@code declaringClass} you must pass\n     *                       in {@code 1} if you want to get the type for the first\n     *                       one or {@code 2} if you want the second one.\n     * @param name           The unqualified name (simple name) of the local class.\n     * @return The type.\n     * @throws ClassNotFoundException the class not found exception\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static Class<Object> getLocalClassType(Class<?> declaringClass, int occurrence, String name)\n            throws ClassNotFoundException {\n        return (Class<Object>) Class.forName(declaringClass.getName() + \"$\" + occurrence + name);\n    }\n\n    /**\n     * Get the type of an anonymous inner class.\n     *\n     * @param declaringClass The class in which the anonymous inner class is declared.\n     * @param occurrence     The occurrence of the anonymous inner class. For example if\n     *                       you have two anonymous inner classes classes in the\n     *                       {@code declaringClass} you must pass in {@code 1} if\n     *                       you want to get the type for the first one or {@code 2}\n     *                       if you want the second one.\n     * @return The type.\n     * @throws ClassNotFoundException the class not found exception\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static Class<Object> getAnonymousInnerClassType(Class<?> declaringClass, int occurrence)\n            throws ClassNotFoundException {\n        return (Class<Object>) Class.forName(declaringClass.getName() + \"$\" + occurrence);\n    }\n\n    /**\n     * Get all fields annotated with a particular annotation. This method\n     * traverses the class hierarchy when checking for the annotation.\n     *\n     * @param object                The object to look for annotations. Note that if're you're\n     *                              passing an object only instance fields are checked, passing a\n     *                              class will only check static fields.\n     * @param annotation            The annotation type to look for.\n     * @param additionalAnnotations Optionally more annotations to look for. If any of the\n     *                              annotations are associated with a particular field it will be\n     *                              added to the resulting {@code Set}.\n     * @return A set of all fields containing the particular annotation.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static Set<Field> getFieldsAnnotatedWith(Object object, Class<? extends Annotation> annotation,\n                                                    Class<? extends Annotation>... additionalAnnotations) {\n        Class<? extends Annotation>[] annotations = null;\n        if (additionalAnnotations == null || additionalAnnotations.length == 0) {\n            annotations = (Class<? extends Annotation>[]) new Class<?>[]{annotation};\n        } else {\n            annotations = (Class<? extends Annotation>[]) new Class<?>[additionalAnnotations.length + 1];\n            annotations[0] = annotation;\n            System.arraycopy(additionalAnnotations, 0, annotations, 1, additionalAnnotations.length);\n        }\n        return getFieldsAnnotatedWith(object, annotations);\n    }\n\n    /**\n     * Get all fields annotated with a particular annotation. This method\n     * traverses the class hierarchy when checking for the annotation.\n     *\n     * @param object          The object to look for annotations. Note that if're you're\n     *                        passing an object only instance fields are checked, passing a\n     *                        class will only check static fields.\n     * @param annotationTypes The annotation types to look for\n     * @return A set of all fields containing the particular annotation(s).\n     * @since 1.3\n     */\n    public static Set<Field> getFieldsAnnotatedWith(Object object, Class<? extends Annotation>[] annotationTypes) {\n        return findAllFieldsUsingStrategy(new FieldAnnotationMatcherStrategy(annotationTypes), object, true,\n                false, getType(object));\n    }\n\n    /**\n     * Get all fields assignable from a particular type. This method traverses\n     * the class hierarchy when checking for the type.\n     *\n     * @param object The object to look for type. Note that if're you're passing an\n     *               object only instance fields are checked, passing a class will\n     *               only check static fields.\n     * @param type   The type to look for.\n     * @return A set of all fields of the particular type.\n     */\n    public static Set<Field> getFieldsOfType(Object object, Class<?> type) {\n        return findAllFieldsUsingStrategy(new AssignableFromFieldTypeMatcherStrategy(type), object, true,\n                false, getType(object));\n    }\n\n    /**\n     * Get all instance fields for a particular object. It returns all fields\n     * regardless of the field modifier and regardless of where in the class\n     * hierarchy a field is located.\n     *\n     * @param object The object whose instance fields to get.\n     * @return All instance fields in the hierarchy. All fields are set to\n     * accessible\n     */\n    public static Set<Field> getAllInstanceFields(Object object) {\n        return findAllFieldsUsingStrategy(new AllFieldsMatcherStrategy(), object, true, true,\n                getUnproxyType(object));\n    }\n\n    /**\n     * Get all static fields for a particular type.\n     *\n     * @param type The class whose static fields to get.\n     * @return All static fields. All fields are set to accessible.\n     */\n    public static Set<Field> getAllStaticFields(Class<?> type) {\n        return findAllFieldsUsingStrategy(new AllFieldsMatcherStrategy(), type, false, false, type);\n    }\n\n    /**\n     * Checks if is class.\n     *\n     * @param argument the argument\n     * @return true, if is class\n     */\n    public static boolean isClass(Object argument) {\n        return argument instanceof Class<?>;\n    }\n\n    /**\n     * Check if parameter types are same.\n     *\n     * @param isVarArgs              Whether or not the method or constructor contains var args.\n     * @param expectedParameterTypes the expected parameter types\n     * @param actualParameterTypes   the actual parameter types\n     * @return if all actual parameter types are assignable from the expected\n     * parameter types, otherwise.\n     */\n    public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes,\n                                                       Class<?>[] actualParameterTypes) {\n        return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match();\n    }\n\n    /**\n     * Gets the field.\n     *\n     * @param fieldName the field name\n     * @param where     the where\n     * @return the field\n     */\n    private static Field getField(String fieldName, Class<?> where) {\n        if (where == null) {\n            throw new IllegalArgumentException(\"where cannot be null\");\n        }\n\n        Field field = null;\n        try {\n            field = where.getDeclaredField(fieldName);\n            field.setAccessible(true);\n        } catch (NoSuchFieldException e) {\n            throw new FieldNotFoundException(\"Field '\" + fieldName + \"' was not found in class \" + where.getName()\n                                                     + \".\");\n        }\n        return field;\n    }\n\n    /**\n     * Find field or throw exception.\n     *\n     * @param fieldType the field type\n     * @param where     the where\n     * @return the field\n     */\n    private static Field findFieldOrThrowException(Class<?> fieldType, Class<?> where) {\n        if (fieldType == null || where == null) {\n            throw new IllegalArgumentException(\"fieldType and where cannot be null\");\n        }\n        Field field = null;\n        for (Field currentField : where.getDeclaredFields()) {\n            currentField.setAccessible(true);\n            if (currentField.getType().equals(fieldType)) {\n                field = currentField;\n                break;\n            }\n        }\n        if (field == null) {\n            throw new FieldNotFoundException(\"Cannot find a field of type \" + fieldType + \"in where.\");\n        }\n        return field;\n    }\n\n    /**\n     * Sets the field.\n     *\n     * @param object     the object\n     * @param value      the value\n     * @param foundField the found field\n     */\n    private static void setField(Object object, Object value, Field foundField) {\n        boolean isStatic = (foundField.getModifiers() & Modifier.STATIC) == Modifier.STATIC;\n        if (isStatic) {\n            setStaticFieldUsingUnsafe(foundField, value);\n        } else {\n            setFieldUsingUnsafe(foundField, object, value);\n        }\n    }\n\n    private static void setStaticFieldUsingUnsafe(final Field field, final Object newValue) {\n        try {\n            field.setAccessible(true);\n            int fieldModifiersMask = field.getModifiers();\n            boolean isFinalModifierPresent = (fieldModifiersMask & Modifier.FINAL) == Modifier.FINAL;\n            if (isFinalModifierPresent) {\n                AccessController.doPrivileged(new PrivilegedAction<Object>() {\n                    @Override\n                    public Object run() {\n                    try {\n                        Unsafe unsafe = getUnsafe();\n                        long offset = unsafe.staticFieldOffset(field);\n                        Object base = unsafe.staticFieldBase(field);\n                        setFieldUsingUnsafe(base, field.getType(), offset, newValue, unsafe);\n                        return null;\n                    } catch (Throwable t) {\n                        throw new RuntimeException(t);\n                    }\n                }});\n            } else {\n                field.set(null, newValue);\n            }\n        } catch (SecurityException ex) {\n            throw new RuntimeException(ex);\n        } catch (IllegalAccessException ex) {\n            throw new RuntimeException(ex);\n        } catch (IllegalArgumentException ex) {\n            throw new RuntimeException(ex);\n        }\n    }\n\n    private static void setFieldUsingUnsafe(final Field field, final Object object, final Object newValue) {\n        try {\n            field.setAccessible(true);\n            int fieldModifiersMask = field.getModifiers();\n            boolean isFinalModifierPresent = (fieldModifiersMask & Modifier.FINAL) == Modifier.FINAL;\n            if (isFinalModifierPresent) {\n                AccessController.doPrivileged(new PrivilegedAction<Object>() {\n                    @Override\n                    public Object run() {\n                        try {\n                            Unsafe unsafe = getUnsafe();\n                            long offset = unsafe.objectFieldOffset(field);\n                            setFieldUsingUnsafe(object, field.getType(), offset, newValue, unsafe);\n                            return null;\n                        } catch (Throwable t) {\n                            throw new RuntimeException(t);\n                        }\n                    }\n                });\n            } else {\n                try {\n                    field.set(object, newValue);\n                } catch (IllegalAccessException ex) {\n                    throw new RuntimeException(ex);\n                }\n            }\n        } catch (SecurityException ex) {\n            throw new RuntimeException(ex);\n        }\n    }\n    \n    private static Unsafe getUnsafe() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {\n        Field field1 = Unsafe.class.getDeclaredField(\"theUnsafe\");\n        field1.setAccessible(true);\n        Unsafe unsafe = (Unsafe) field1.get(null);\n        return unsafe;\n    }\n\n    private static void setFieldUsingUnsafe(Object base, Class type, long offset, Object newValue, Unsafe unsafe) {\n        if (type == Integer.TYPE) {\n            unsafe.putInt(base, offset, ((Integer) newValue));\n        } else if (type == Short.TYPE) {\n            unsafe.putShort(base, offset, ((Short) newValue));\n        } else if (type == Long.TYPE) {\n            unsafe.putLong(base, offset, ((Long) newValue));\n        } else if (type == Byte.TYPE) {\n            unsafe.putByte(base, offset, ((Byte) newValue));\n        } else if (type == Boolean.TYPE) {\n            unsafe.putBoolean(base, offset, ((Boolean) newValue));\n        } else if (type == Float.TYPE) {\n            unsafe.putFloat(base, offset, ((Float) newValue));\n        } else if (type == Double.TYPE) {\n            unsafe.putDouble(base, offset, ((Double) newValue));\n        } else if (type == Character.TYPE) {\n            unsafe.putChar(base, offset, ((Character) newValue));\n        } else {\n            unsafe.putObject(base, offset, newValue);\n        }\n    }\n\n    /**\n     * Concatenate strings.\n     *\n     * @param stringsToConcatenate the strings to concatenate\n     * @return the string\n     */\n    private static String concatenateStrings(String... stringsToConcatenate) {\n        StringBuilder builder = new StringBuilder();\n        final int stringsLength = stringsToConcatenate.length;\n        for (int i = 0; i < stringsLength; i++) {\n            if (i == stringsLength - 1 && stringsLength != 1) {\n                builder.append(\" or \");\n            } else if (i != 0) {\n                builder.append(\", \");\n            }\n            builder.append(stringsToConcatenate[i]);\n        }\n        return builder.toString();\n    }\n\n    /**\n     * Checks if is potential var args method.\n     *\n     * @param method    the method\n     * @param arguments the arguments\n     * @return true, if is potential var args method\n     */\n    private static boolean isPotentialVarArgsMethod(Method method, Object[] arguments) {\n        return doesParameterTypesMatchForVarArgsInvocation(method.isVarArgs(), method.getParameterTypes(), arguments);\n    }\n\n    /**\n     * Does parameter types match for var args invocation.\n     *\n     * @param isVarArgs      the is var args\n     * @param parameterTypes the parameter types\n     * @param arguments      the arguments\n     * @return true, if successful\n     */\n     static boolean doesParameterTypesMatchForVarArgsInvocation(boolean isVarArgs, Class<?>[] parameterTypes,\n                                                                       Object[] arguments) {\n        if (isVarArgs && arguments != null && arguments.length >= 1 && parameterTypes != null\n                    && parameterTypes.length >= 1) {\n            final Class<?> componentType = parameterTypes[parameterTypes.length - 1].getComponentType();\n            final Object lastArgument = arguments[arguments.length - 1];\n            if (lastArgument != null) {\n                final Class<?> lastArgumentTypeAsPrimitive = getTypeAsPrimitiveIfWrapped(lastArgument);\n                final Class<?> varArgsParameterTypeAsPrimitive = getTypeAsPrimitiveIfWrapped(componentType);\n                isVarArgs = varArgsParameterTypeAsPrimitive.isAssignableFrom(lastArgumentTypeAsPrimitive);\n            }\n        }\n        return isVarArgs && checkArgumentTypesMatchParameterTypes(isVarArgs, parameterTypes, arguments);\n    }\n\n    /**\n     * Get the type of an object and convert it to primitive if the type has a\n     * primitive counter-part. E.g. if object is an instance of\n     * {@code java.lang.Integer} this method will return\n     * {@code int.class}.\n     *\n     * @param object The object whose type to get.\n     * @return the type as primitive if wrapped\n     */\n    static Class<?> getTypeAsPrimitiveIfWrapped(Object object) {\n        if (object != null) {\n            final Class<?> firstArgumentType = getType(object);\n            final Class<?> firstArgumentTypeAsPrimitive = PrimitiveWrapper.hasPrimitiveCounterPart(firstArgumentType) ? PrimitiveWrapper\n                                                                                                                                .getPrimitiveFromWrapperType(firstArgumentType) : firstArgumentType;\n            return firstArgumentTypeAsPrimitive;\n        }\n        return null;\n    }\n\n    /**\n     * Set the values of multiple instance fields defined in a context using\n     * reflection. The values in the context will be assigned to values on the\n     * {@code instance}. This method will traverse the class hierarchy when\n     * searching for the fields. Example usage:\n     *\n     * Given:\n     *\n     * <pre>\n     * public class MyContext {\n     * \tprivate String myString = &quot;myString&quot;;\n     * \tprotected int myInt = 9;\n     * }\n     *\n     * public class MyInstance {\n     * \tprivate String myInstanceString;\n     * \tprivate int myInstanceInt;\n     *\n     * }\n     * </pre>\n     *\n     * then\n     *\n     * <pre>\n     * Whitebox.setInternalStateFromContext(new MyInstance(), new MyContext());\n     * </pre>\n     *\n     * will set the instance variables of {@code myInstance} to the values\n     * specified in {@code MyContext}.\n     *\n     * @param object             the object\n     * @param context            The context where the fields are defined.\n     * @param additionalContexts Optionally more additional contexts.\n     */\n    public static void setInternalStateFromContext(Object object, Object context, Object[] additionalContexts) {\n        setInternalStateFromContext(object, context, FieldMatchingStrategy.MATCHING);\n        if (additionalContexts != null && additionalContexts.length > 0) {\n            for (Object additionContext : additionalContexts) {\n                setInternalStateFromContext(object, additionContext, FieldMatchingStrategy.MATCHING);\n            }\n        }\n    }\n\n    public static void setInternalStateFromContext(Object object, Object context, FieldMatchingStrategy strategy) {\n        if (isClass(context)) {\n            copyState(object, getType(context), strategy);\n        } else {\n            copyState(object, context, strategy);\n        }\n    }\n\n    /**\n     * Set the values of multiple static fields defined in a context using\n     * reflection. The values in the context will be assigned to values on the\n     * {@code classOrInstance}. This method will traverse the class\n     * hierarchy when searching for the fields. Example usage:\n     *\n     * Given:\n     *\n     * <pre>\n     * public class MyContext {\n     * \tprivate static String myString = &quot;myString&quot;;\n     * \tprotected static int myInt = 9;\n     * }\n     *\n     * public class MyInstance {\n     * \tprivate static String myInstanceString;\n     * \tprivate static int myInstanceInt;\n     *\n     * }\n     * </pre>\n     *\n     * then\n     *\n     * <pre>\n     * Whitebox.setInternalStateFromContext(MyInstance.class, MyContext.class);\n     * </pre>\n     *\n     * will set the static variables of {@code MyInstance} to the values\n     * specified in {@code MyContext}.\n     *\n     * @param object             the object\n     * @param context            The context where the fields are defined.\n     * @param additionalContexts Optionally more additional contexts.\n     */\n    public static void setInternalStateFromContext(Object object, Class<?> context, Class<?>[] additionalContexts) {\n        setInternalStateFromContext(object, context, FieldMatchingStrategy.MATCHING);\n        if (additionalContexts != null && additionalContexts.length > 0) {\n            for (Class<?> additionContext : additionalContexts) {\n                setInternalStateFromContext(object, additionContext, FieldMatchingStrategy.MATCHING);\n            }\n        }\n    }\n\n    /**\n     * Copy state.\n     *\n     * @param object   the object\n     * @param context  the context\n     * @param strategy The field matching strategy.\n     */\n    static void copyState(Object object, Object context, FieldMatchingStrategy strategy) {\n        if (object == null) {\n            throw new IllegalArgumentException(\"object to set state cannot be null\");\n        } else if (context == null) {\n            throw new IllegalArgumentException(\"context cannot be null\");\n        } else if (strategy == null) {\n            throw new IllegalArgumentException(\"strategy cannot be null\");\n        }\n\n        Set<Field> allFields = isClass(context) ? getAllStaticFields(getType(context)) : getAllInstanceFields(context);\n        for (Field field : allFields) {\n            try {\n                final boolean isStaticField = Modifier.isStatic(field.getModifiers());\n                setInternalState(isStaticField ? getType(object) : object, field.getType(), field.get(context));\n            } catch (FieldNotFoundException e) {\n                if (strategy == FieldMatchingStrategy.STRICT) {\n                    throw e;\n                }\n            } catch (IllegalAccessException e) {\n                // Should never happen\n                throw new RuntimeException(\n                                                  \"Internal Error: Failed to get the field value in method setInternalStateFromContext.\", e);\n            }\n        }\n    }\n\n    /**\n     * Assert object in get internal state is not null.\n     *\n     * @param object the object\n     */\n    private static void assertObjectInGetInternalStateIsNotNull(Object object) {\n        if (object == null) {\n            throw new IllegalArgumentException(\"The object containing the field cannot be null\");\n        }\n    }\n\n    /**\n     * Convert parameter types to primitive.\n     *\n     * @param parameterTypes the parameter types\n     * @return the class[]\n     */\n    private static Class<?>[] convertParameterTypesToPrimitive(Class<?>[] parameterTypes) {\n        Class<?>[] converted = new Class<?>[parameterTypes.length];\n        for (int i = 0; i < parameterTypes.length; i++) {\n            Class<?> primitiveWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(parameterTypes[i]);\n            if (primitiveWrapperType == null) {\n                converted[i] = parameterTypes[i];\n            } else {\n                converted[i] = primitiveWrapperType;\n            }\n        }\n        return converted;\n    }\n\n    public static <T> void copyToMock(T from, T mock) {\n        copy(from, mock, from.getClass());\n    }\n\n    public static<T> void copyToRealObject(T from, T to) {\n        copy(from, to, from.getClass());\n    }\n\n    private static<T> void copy(T from, T to, Class<?> fromClazz) {\n        while (fromClazz != Object.class) {\n            copyValues(from, to, fromClazz);\n            fromClazz = fromClazz.getSuperclass();\n        }\n    }\n\n    private static<T> void copyValues(T from, T mock, Class<?> classFrom) {\n        Field[] fields = classFrom.getDeclaredFields();\n\n        for (Field field : fields) {\n            // ignore static fields\n            if (Modifier.isStatic(field.getModifiers())) {\n                continue;\n            }\n            boolean accessible = field.isAccessible();\n            try {\n                field.setAccessible(true);\n                copyValue(from, mock, field);\n            } catch (Exception ignored) {\n                //Ignore - be lenient - if some field cannot be copied then let's be it\n            } finally {\n                field.setAccessible(accessible);\n            }\n        }\n    }\n\n    private static <T> void copyValue(T from, T to, Field field) throws IllegalAccessException {\n        Object value = field.get(from);\n        field.set(to, value);\n    }\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/comparator/ComparatorFactory.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.reflect.internal.comparator;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\nimport java.util.Comparator;\n\n/**\n *  This comparator factory is used to create Comparators for\n *  {@link org.powermock.reflect.Whitebox} which are used to find best candidates\n *  for constructor and method invocation.\n *  @see org.powermock.reflect.internal.WhiteboxImpl#getBestMethodCandidate(Class, String, Class[], boolean)\n *  @see org.powermock.reflect.internal.WhiteboxImpl#getBestCandidateConstructor(Class, Class[], Object[])\n */\npublic class ComparatorFactory {\n\n    private ComparatorFactory() {\n    }\n\n    public static Comparator<Constructor> createConstructorComparator(){\n        return new ConstructorComparator(new ParametersComparator());\n    }\n\n    public static Comparator<Method> createMethodComparator(){\n        return new MethodComparator(new ParametersComparator());\n    }\n\n\n    public static class ConstructorComparator implements Comparator<Constructor> {\n        private final ParametersComparator parametersComparator;\n\n        private ConstructorComparator(ParametersComparator parametersComparator) {\n\n            this.parametersComparator = parametersComparator;\n        }\n\n        @Override\n        public int compare(Constructor constructor1, Constructor constructor2) {\n            final Class<?>[] parameters1 = constructor1.getParameterTypes();\n            final Class<?>[] parameters2 = constructor2.getParameterTypes();\n            return parametersComparator.compare(parameters1,parameters2);\n        }\n    }\n\n    /**\n     *\n     */\n    public static class MethodComparator implements Comparator<Method> {\n        private final ParametersComparator parametersComparator;\n\n        private MethodComparator(ParametersComparator parametersComparator) {\n\n            this.parametersComparator = parametersComparator;\n        }\n\n        @Override\n        public int compare(Method m1, Method m2) {\n            final Class<?>[] typesMethod1 = m1.getParameterTypes();\n            final Class<?>[] typesMethod2 = m2.getParameterTypes();\n            return parametersComparator.compare(typesMethod1, typesMethod2);\n\n        }\n    }\n\n    private static class ParametersComparator implements Comparator<Class[]>{\n\n        @Override\n        public int compare(Class[] params1, Class[] params2) {\n            final int size = params1.length;\n            for (int i = 0; i < size; i++) {\n                Class<?> type1 = params1[i];\n                Class<?> type2 = params2[i];\n                if (!type1.equals(type2)) {\n                    if (type1.isAssignableFrom(type2)) {\n                        if (!type1.isArray() && type2.isArray()) {\n                            return -1;\n                        }\n                        return 1;\n                    } else {\n                        if (type1.isArray() && !type2.isArray()) {\n                            return 1;\n                        }\n                        return -1;\n                    }\n                }\n            }\n            return 0;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/AllFieldsMatcherStrategy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.matcherstrategies;\n\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\n\nimport java.lang.reflect.Field;\n\npublic class AllFieldsMatcherStrategy extends FieldMatcherStrategy {\n\n    @Override\n    public boolean matches(Field field) {\n        return true;\n    }\n\n    @Override\n    public void notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException {\n        throw new FieldNotFoundException(String.format(\"No %s fields were declared in %s.\", isInstanceField ? \"instance\" : \"static\", type.getName()));\n    }\n}"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/AssignableFromFieldTypeMatcherStrategy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.matcherstrategies;\n\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\nimport org.powermock.reflect.internal.primitivesupport.PrimitiveWrapper;\n\nimport java.lang.reflect.Field;\n\npublic class AssignableFromFieldTypeMatcherStrategy extends FieldTypeMatcherStrategy {\n\n\tprivate final Class<?> primitiveCounterpart;\n\n\tpublic AssignableFromFieldTypeMatcherStrategy(Class<?> fieldType) {\n\t\tsuper(fieldType);\n\t\tprimitiveCounterpart = PrimitiveWrapper.getPrimitiveFromWrapperType(expectedFieldType);\n\t}\n\n\t@Override\n\tpublic boolean matches(Field field) {\n\t\tClass<?> actualFieldType = field.getType();\n\t\treturn actualFieldType.isAssignableFrom(expectedFieldType)\n\t\t\t\t|| (primitiveCounterpart != null && actualFieldType.isAssignableFrom(primitiveCounterpart));\n\t}\n\n\t@Override\n\tpublic void notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException {\n\t\tthrow new FieldNotFoundException(String.format(\"No %s field assignable from \\\"%s\\\" could be found in the class hierarchy of %s.\",\n\t\t\t\tisInstanceField ? \"instance\" : \"static\", expectedFieldType.getName(), type.getName()));\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"type \" + (primitiveCounterpart == null ? expectedFieldType.getName() : primitiveCounterpart.getName());\n\t}\n}"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/AssignableToFieldTypeMatcherStrategy.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.matcherstrategies;\n\nimport java.lang.reflect.Field;\n\npublic class AssignableToFieldTypeMatcherStrategy extends FieldTypeMatcherStrategy {\n\n\tpublic AssignableToFieldTypeMatcherStrategy(Class<?> fieldType) {\n\t\tsuper(fieldType);\n\t}\n\n\t@Override\n\tpublic boolean matches(Field field) {\n\t\treturn expectedFieldType.isAssignableFrom(field.getType());\n\t}\n}"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldAnnotationMatcherStrategy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.matcherstrategies;\n\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\n\npublic class FieldAnnotationMatcherStrategy extends FieldMatcherStrategy {\n\n\tfinal Class<? extends Annotation>[] annotations;\n\n\tpublic FieldAnnotationMatcherStrategy(Class<? extends Annotation>[] annotations) {\n\t\tif (annotations == null || annotations.length == 0) {\n\t\t\tthrow new IllegalArgumentException(\"You must specify atleast one annotation.\");\n\t\t}\n\t\tthis.annotations = annotations;\n\t}\n\n\t@Override\n\tpublic boolean matches(Field field) {\n\t\tfor (Class<? extends Annotation> annotation : annotations) {\n\t\t\tif (field.isAnnotationPresent(annotation)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException {\n\t\tthrow new FieldNotFoundException(\"No field that has any of the annotation types \\\"\" + getAnnotationNames()\n\t\t\t\t+ \"\\\" could be found in the class hierarchy of \" + type.getName() + \".\");\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"annotations \" + getAnnotationNames();\n\t}\n\n\tprivate String getAnnotationNames() {\n\t\tfinal StringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < annotations.length; i++) {\n\t\t\tbuilder.append(annotations[i].getName());\n\t\t\tif (i != annotations.length - 1) {\n\t\t\t\tbuilder.append(\", \");\n\t\t\t}\n\t\t}\n\t\treturn builder.toString();\n\t}\n}"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldMatcherStrategy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.matcherstrategies;\n\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\n\nimport java.lang.reflect.Field;\n\n/**\n * Class that should be implemented by field matching strategies.\n */\npublic abstract class FieldMatcherStrategy {\n\n    /**\n     * A field matcher that checks if a field matches a given criteria.\n     * \n     * @param field\n     *            The field to check whether it matches the strategy or not.\n     * @return {@code true} if this field matches the strategy,\n     *         {@code false} otherwise.\n     * \n     */\n    public abstract boolean matches(Field field);\n\n    /**\n     * Throws an {@link FieldNotFoundException} if the strategy criteria could\n     * not be found.\n     * \n     * @param type\n     *            The type of the object that was not found.\n     * @param isInstanceField\n     *            {@code true} if the field that was looked after was an\n     *            instance field or {@code false} if it was a static field.\n     */\n    public abstract void notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException;\n}"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldNameMatcherStrategy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.matcherstrategies;\n\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\n\nimport java.lang.reflect.Field;\n\npublic class FieldNameMatcherStrategy extends FieldMatcherStrategy {\n\n    private final String fieldName;\n\n    public FieldNameMatcherStrategy(String fieldName) {\n        if (fieldName == null || fieldName.equals(\"\") || fieldName.startsWith(\" \")) {\n            throw new IllegalArgumentException(\"field name cannot be null.\");\n        }\n        this.fieldName = fieldName;\n    }\n\n    @Override\n    public boolean matches(Field field) {\n        return fieldName.equals(field.getName());\n    }\n\n    @Override\n    public void notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException {\n        throw new FieldNotFoundException(String.format(\"No %s field named \\\"%s\\\" could be found in the class hierarchy of %s.\",\n                isInstanceField ? \"instance\" : \"static\", fieldName, type.getName()));\n    }\n\n    @Override\n    public String toString() {\n        return \"fieldName \" + fieldName;\n    }\n}"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldTypeMatcherStrategy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.matcherstrategies;\n\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\n\nimport java.lang.reflect.Field;\n\npublic class FieldTypeMatcherStrategy extends FieldMatcherStrategy {\n\n    final Class<?> expectedFieldType;\n\n    public FieldTypeMatcherStrategy(Class<?> fieldType) {\n        if (fieldType == null) {\n            throw new IllegalArgumentException(\"field type cannot be null.\");\n        }\n        this.expectedFieldType = fieldType;\n    }\n\n    @Override\n    public boolean matches(Field field) {\n        return expectedFieldType.equals(field.getType());\n    }\n\n    @Override\n    public void notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException {\n        throw new FieldNotFoundException(String.format(\"No %s field of type \\\"%s\\\" could be found in the class hierarchy of %s.\",\n                isInstanceField ? \"instance\" : \"static\", expectedFieldType.getName(), type.getName()));\n    }\n\n    @Override\n    public String toString() {\n        return \"type \" + expectedFieldType.getName();\n    }\n}"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/BoxedWrapper.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.primitivesupport;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The purpose of the Primitive Wrapper is to provide methods that deals with\n * translating wrapper types to its related primitive type.\n */\npublic class BoxedWrapper {\n\tprivate static final Map<Class<?>, Class<?>> boxedWrapper = new HashMap<Class<?>, Class<?>>();\n\n\tstatic {\n\t\tboxedWrapper.put(int.class, Integer.class);\n\t\tboxedWrapper.put(long.class, Long.class);\n\t\tboxedWrapper.put(float.class, Float.class);\n\t\tboxedWrapper.put(double.class, Double.class);\n\t\tboxedWrapper.put(boolean.class, Boolean.class);\n\t\tboxedWrapper.put(byte.class, Byte.class);\n\t\tboxedWrapper.put(short.class, Short.class);\n\t\tboxedWrapper.put(char.class, Character.class);\n\t}\n\n\t/**\n\t * Get the wrapped counter part from a primitive type. For example:\n\t * <p>\n\t * \n\t * {@code getBoxedFromPrimitiveType(int.class)} will return\n\t * {@code Integer.class}.\n\t * \n\t * \n\t * @param primitiveType\n\t *            The primitive type to convert to its wrapper counter part.\n\t * @return The boxed counter part or {@code null} if the class did\n\t *         not have a boxed counter part.\n\t * \n\t */\n\tpublic static Class<?> getBoxedFromPrimitiveType(Class<?> primitiveType) {\n\t\treturn boxedWrapper.get(primitiveType);\n\t}\n\n\t/**\n\t * Returns {@code true} if {@code type} has a primitive\n\t * counter-part. E.g. if {@code type} if {@code Integer} then this\n\t * method will return {@code true}.\n\t * \n\t * @param type\n\t *            The type to check whether or not it has a primitive\n\t *            counter-part.\n\t * @return {@code true} if this type has a primitive counter-part.\n\t */\n\tpublic static boolean hasBoxedCounterPart(Class<?> type) {\n\t\treturn boxedWrapper.containsKey(type);\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/PrimitiveWrapper.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal.primitivesupport;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The purpose of the Primitive Wrapper is to provide methods that deals with\n * translating wrapper types to its related primitive type.\n */\npublic class PrimitiveWrapper {\n\tprivate static final Map<Class<?>, Class<?>> primitiveWrapper = new HashMap<Class<?>, Class<?>>();\n\n\tstatic {\n\t\tprimitiveWrapper.put(Integer.class, int.class);\n\t\tprimitiveWrapper.put(Long.class, long.class);\n\t\tprimitiveWrapper.put(Float.class, float.class);\n\t\tprimitiveWrapper.put(Double.class, double.class);\n\t\tprimitiveWrapper.put(Boolean.class, boolean.class);\n\t\tprimitiveWrapper.put(Byte.class, byte.class);\n\t\tprimitiveWrapper.put(Short.class, short.class);\n\t\tprimitiveWrapper.put(Character.class, char.class);\n\t}\n\n\t/**\n\t * Convert all wrapper types in {@code types} to their primitive\n\t * counter parts.\n\t * \n\t * @param types\n\t *            The array of types that should be converted.\n\t * @return A new array where all wrapped types have been converted to their\n\t *         primitive counter part.\n\t */\n\tpublic static Class<?>[] toPrimitiveType(Class<?>[] types) {\n\t\tif (types == null) {\n\t\t\tthrow new IllegalArgumentException(\"types cannot be null\");\n\t\t}\n\n\t\tClass<?>[] convertedTypes = new Class<?>[types.length];\n\t\tfor (int i = 0; i < types.length; i++) {\n\t\t\tfinal Class<?> originalType = types[i];\n\t\t\tClass<?> primitiveType = primitiveWrapper.get(originalType);\n\t\t\tif (primitiveType == null) {\n\t\t\t\tconvertedTypes[i] = originalType;\n\t\t\t} else {\n\t\t\t\tconvertedTypes[i] = primitiveType;\n\t\t\t}\n\t\t}\n\t\treturn convertedTypes;\n\t}\n\n\t/**\n\t * Get the primitive counter part from a wrapped type. For example:\n\t * <p>\n\t * \n\t * {@code getPrimitiveFromWrapperType(Integer.class)} will return\n\t * {@code int.class}.\n\t * \n\t * \n\t * @param wrapperType\n\t *            The wrapper type to convert to its primitive counter part.\n\t * @return The primitive counter part or {@code null} if the class did\n\t *         not have a primitive counter part.\n\t * \n\t */\n\tpublic static Class<?> getPrimitiveFromWrapperType(Class<?> wrapperType) {\n\t\treturn primitiveWrapper.get(wrapperType);\n\t}\n\n\t/**\n\t * Returns {@code true} if {@code type} has a primitive\n\t * counter-part. E.g. if {@code type} if {@code Integer} then this\n\t * method will return {@code true}.\n\t * \n\t * @param type\n\t *            The type to check whether or not it has a primitive\n\t *            counter-part.\n\t * @return {@code true} if this type has a primitive counter-part.\n\t */\n\tpublic static boolean hasPrimitiveCounterPart(Class<?> type) {\n\t\treturn primitiveWrapper.containsKey(type);\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/ProxyFrameworks.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\n\npublic class ProxyFrameworks {\n    \n    private static final UnproxiedTypeFactory UNPROXIED_TYPE_FACTORY = new UnproxiedTypeFactory();\n\n    public UnproxiedType getUnproxiedType(Class<?> type) {\n\n        if (type == null){\n            return null;\n        }\n\n        if (isJavaProxy(type)){\n            return UNPROXIED_TYPE_FACTORY.createFromInterfaces(type.getInterfaces());\n        }\n\n        if (isCglibProxyClass(type)) {\n            return UNPROXIED_TYPE_FACTORY.createFromSuperclassAndInterfaces(type.getSuperclass(), type.getInterfaces());\n        }\n\n        return UNPROXIED_TYPE_FACTORY.createFromType(type);\n    }\n    \n    public UnproxiedType getUnproxiedType(Object o) {\n        if (o == null) {\n            return null;\n        }\n        return getUnproxiedType(o.getClass());\n    }\n\n    private boolean isJavaProxy(Class<?> clazz) {\n        return (clazz != null && Proxy.isProxyClass(clazz));\n    }\n\n    private boolean isCglibProxyClass(Class<?> clazz) {\n        if (clazz == null){\n            return false;\n        }\n        Method[] methods = clazz.getDeclaredMethods();\n        for(Method m: methods){\n            if(isCglibCallbackMethod(m)) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    private boolean isCglibCallbackMethod(Method m) {\n        return \"CGLIB$SET_THREAD_CALLBACKS\".equals(m.getName()) && m.getParameterTypes().length == 1;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedType.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\npublic interface UnproxiedType {\n    Class<?> getOriginalType();\n    \n    Class<?>[] getInterfaces();\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedTypeFactory.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass UnproxiedTypeFactory {\n    \n    private static final String[] RESTRICTED_INTERFACES = {\n        \"cglib.proxy.Factory\"\n    };\n    \n    UnproxiedType createFromInterfaces(Class<?>[] interfaces) {\n        Class<?>[] filteredInterfaces = filterInterfaces(interfaces);\n        if (filteredInterfaces.length == 0){\n            return new UnproxiedTypeImpl(Object.class);\n        }\n        if (filteredInterfaces.length == 1){\n            return new UnproxiedTypeImpl(filteredInterfaces[0]);\n        }\n        return new UnproxiedTypeImpl(filteredInterfaces);\n    }\n    \n    UnproxiedType createFromSuperclassAndInterfaces(Class<?> superclass, Class<?>[] interfaces) {\n        if (Object.class.equals(superclass)){\n           return createFromInterfaces(interfaces);\n        }\n    \n        Class<?>[] filteredInterfaces = filterInterfaces(interfaces);\n        \n        return new UnproxiedTypeImpl(superclass, filteredInterfaces);\n    }\n    \n    UnproxiedType createFromType(Class<?> type) {\n        return new UnproxiedTypeImpl(type);\n    }\n    \n    private Class<?>[] filterInterfaces(Class<?>[] interfaces) {\n        List<Class<?>> filtered = new ArrayList<Class<?>>();\n    \n        for (Class<?> anInterface : interfaces) {\n            if(!isMockFrameworkInterface(anInterface)){\n                filtered.add(anInterface);\n            }\n        }\n    \n        return filtered.toArray(new Class[filtered.size()]);\n    }\n    \n    private boolean isMockFrameworkInterface(Class<?> anInterface) {\n        String name = anInterface.getName();\n        for (String restrictedInterface : RESTRICTED_INTERFACES) {\n            if (name.contains(restrictedInterface)){\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    private static class UnproxiedTypeImpl implements UnproxiedType {\n        \n        private final Class<?> type;\n        private final Class<?>[] interfaces;\n    \n        private UnproxiedTypeImpl(Class<?> type) {\n            this.type = type;\n            this.interfaces = new Class[0];\n        }\n    \n        private UnproxiedTypeImpl(Class<?>[] interfaces) {\n            this.type = null;\n            this.interfaces = interfaces;\n        }\n    \n        private UnproxiedTypeImpl(Class<?> type, Class<?>[] interfaces) {\n            this.type = type;\n            this.interfaces = interfaces;\n        }\n    \n        @Override\n        public Class<?> getOriginalType() {\n            return type;\n        }\n    \n        @Override\n        public Class<?>[] getInterfaces() {\n            return interfaces;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/main/java/org/powermock/reflect/matching/FieldMatchingStrategy.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.matching;\n\n/**\n * Defines strategies for field matching.\n */\npublic enum FieldMatchingStrategy {\n\t/**\n\t * All fields in the context must match <i>exactly</i> the fields in the\n\t * target instance or class. This means that an exception will be thrown\n\t * unless all fields in the context are found in the target.\n\t */\n\tSTRICT,\n\t/**\n\t * All fields in the context are copied to the target instance or class. The\n\t * context may contain additional fields not present in the target. Only\n\t * fields that may be copied from the context to the target are taken into\n\t * consideration. An exception will not be thrown if a field exists in the\n\t * context but is non-existent in the target.\n\t */\n\tMATCHING\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxGetFieldTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect;\n\nimport org.junit.Test;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.lang.reflect.Field;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\n/**\n * A test case to demonstrate an issue\n * {@link org.powermock.reflect.internal.WhiteboxImpl#getField(Class, String)}.\n * As the class hierarchy for the given Class is ascended, if the field is not\n * found in the parent class, the interfaces are checked before the grandparent\n * class. The problem is that the getSuperclass() method will always return null\n * for the Class representing the interface. The current implementation of\n * WhiteboxImpl blindly adds this null to the {@code examine} LinkedList.\n * \n * @author Ben Chatelain\n */\npublic class WhiteBoxGetFieldTest {\n\n\tinterface SomeInterface {\n\t}\n\n\tclass GrandParentClass {\n\t\t@SuppressWarnings(\"unused\")\n\t\tprivate String fieldA;\n\t}\n\n\tclass ParentClass extends GrandParentClass {\n\t}\n\n\tclass ClassUnderTest extends ParentClass implements SomeInterface {\n\t\t@SuppressWarnings(\"unused\")\n\t\tprivate String fieldB;\n\t}\n\n\t/**\n\t * Verifies that <a\n\t * href=\"http://code.google.com/p/powermock/issues/detail?id=149\">issue\n\t * 149</a> has been resolved.\n\t */\n\t@Test\n\tpublic void testGetField() {\n\t\tField fieldA = WhiteboxImpl.getField(ClassUnderTest.class, \"fieldA\");\n\t\tassertThat(fieldA).isNotNull();\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.powermock.reflect.context.ClassFieldsNotInTargetContext;\nimport org.powermock.reflect.context.InstanceFieldsNotInTargetContext;\nimport org.powermock.reflect.context.MyContext;\nimport org.powermock.reflect.context.MyIntContext;\nimport org.powermock.reflect.context.MyStringContext;\nimport org.powermock.reflect.context.OneInstanceAndOneStaticFieldOfSameTypeContext;\nimport org.powermock.reflect.exceptions.FieldNotFoundException;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyFieldsFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport org.powermock.reflect.matching.FieldMatchingStrategy;\nimport org.powermock.reflect.testclasses.AbstractClass;\nimport org.powermock.reflect.testclasses.AnInterface;\nimport org.powermock.reflect.testclasses.Child;\nimport org.powermock.reflect.testclasses.ClassWithAMethod;\nimport org.powermock.reflect.testclasses.ClassWithChildThatHasInternalState;\nimport org.powermock.reflect.testclasses.ClassWithInterfaceConstructors;\nimport org.powermock.reflect.testclasses.ClassWithInterfaceConstructors.ConstructorInterface;\nimport org.powermock.reflect.testclasses.ClassWithInterfaceConstructors.ConstructorInterfaceImpl;\nimport org.powermock.reflect.testclasses.ClassWithInternalState;\nimport org.powermock.reflect.testclasses.ClassWithList;\nimport org.powermock.reflect.testclasses.ClassWithObjectConstructors;\nimport org.powermock.reflect.testclasses.ClassWithOverloadedConstructors;\nimport org.powermock.reflect.testclasses.ClassWithOverloadedMethods;\nimport org.powermock.reflect.testclasses.ClassWithOverriddenMethod;\nimport org.powermock.reflect.testclasses.ClassWithPrimitiveConstructors;\nimport org.powermock.reflect.testclasses.ClassWithPrivateMethods;\nimport org.powermock.reflect.testclasses.ClassWithSerializableState;\nimport org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName;\nimport org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameNameOneWithoutParameters;\nimport org.powermock.reflect.testclasses.ClassWithSimpleInternalState;\nimport org.powermock.reflect.testclasses.ClassWithStaticAndInstanceInternalStateOfSameType;\nimport org.powermock.reflect.testclasses.ClassWithStaticMethod;\nimport org.powermock.reflect.testclasses.ClassWithUniquePrivateMethods;\nimport org.powermock.reflect.testclasses.ClassWithVarArgsConstructor;\nimport org.powermock.reflect.testclasses.ClassWithVarArgsConstructor2;\n\nimport java.io.InputStream;\nimport java.io.Serializable;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.sql.Connection;\nimport java.util.Set;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertSame;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\n\n/**\n * Tests the WhiteBox's functionality.\n */\npublic class WhiteBoxTest {\n\n\t@Rule\n\tpublic ExpectedException expectedException = ExpectedException.none();\n\n\t@Test\n\tpublic void testFindMethod_classContainingMethodWithNoParameters() throws Exception {\n\t\tMethod expected = ClassWithSeveralMethodsWithSameNameOneWithoutParameters.class.getMethod(\"getDouble\");\n\t\tMethod actual = WhiteboxImpl.findMethodOrThrowException(\n\t\t\t\tClassWithSeveralMethodsWithSameNameOneWithoutParameters.class, \"getDouble\");\n\t\tassertEquals(expected, actual);\n\t}\n\n    @Test\n    public void testFindMethod_classContainingOnlyMethodsWithParameters() throws Exception {\n        try {\n            WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, \"getDouble\");\n            fail(\"Should throw runtime exception!\");\n        } catch (RuntimeException e) {\n            assertTrue(\"Error message did not match\", e.getMessage().contains(\n                    \"Several matching methods found, please specify the argument parameter types\"));\n        }\n    }\n\n    @Test\n    public void testFindMethod_noMethodFound() throws Exception {\n        try {\n            WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, \"getDouble2\");\n            fail(\"Should throw runtime exception!\");\n        } catch (RuntimeException e) {\n            assertEquals(\"Error message did not match\",\n                         \"No method found with name 'getDouble2' with parameter types: [ <none> ] in class \"\n                                 + ClassWithSeveralMethodsWithSameName.class.getName() + \".\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testGetInternalState_object() throws Exception {\n        ClassWithInternalState tested = new ClassWithInternalState();\n        tested.increaseInteralState();\n        Object internalState = Whitebox.getInternalState(tested, \"internalState\");\n        assertTrue(\"InternalState should be instanceof Integer\", internalState instanceof Integer);\n        assertEquals(1, internalState);\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    @Test\n    public void testGetInternalState_parmaterizedType() throws Exception {\n        ClassWithInternalState tested = new ClassWithInternalState();\n        tested.increaseInteralState();\n        int internalState = Whitebox.getInternalState(tested, \"internalState\", tested.getClass(), int.class);\n        assertEquals(1, internalState);\n    }\n\n    @Test\n    public void testSetInternalState() throws Exception {\n        ClassWithInternalState tested = new ClassWithInternalState();\n        tested.increaseInteralState();\n        Whitebox.setInternalState(tested, \"anotherInternalState\", 2);\n        assertEquals(2, tested.getAnotherInternalState());\n    }\n\n    @Test\n    public void testSetInternalStateWithMultipleValues() throws Exception {\n        ClassWithInternalState tested = new ClassWithInternalState();\n        final ClassWithPrivateMethods classWithPrivateMethods = new ClassWithPrivateMethods();\n        final String stringState = \"someStringState\";\n        Whitebox.setInternalState(tested, classWithPrivateMethods, stringState);\n        assertEquals(stringState, Whitebox.getInternalState(tested, String.class));\n        assertSame(classWithPrivateMethods, Whitebox.getInternalState(tested, ClassWithPrivateMethods.class));\n    }\n\n    @Test\n    public void testSetInternalState_superClass() throws Exception {\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        tested.increaseInteralState();\n        Whitebox.setInternalState(tested, \"anotherInternalState\", 2, ClassWithInternalState.class);\n        assertEquals(2, tested.getAnotherInternalState());\n    }\n\n    @Test\n    public void testGetInternalState_superClass_object() throws Exception {\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Object internalState = Whitebox.getInternalState(tested, \"internalState\", ClassWithInternalState.class);\n        assertEquals(0, internalState);\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    @Test\n    public void testGetInternalState_superClass_parameterized() throws Exception {\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        int internalState = Whitebox.getInternalState(tested, \"internalState\", ClassWithInternalState.class, int.class);\n        assertEquals(0, internalState);\n    }\n\n    @Test\n    public void testInvokePrivateMethod_primtiveType() throws Exception {\n        assertTrue(Whitebox.<Boolean>invokeMethod(new ClassWithPrivateMethods(), \"primitiveMethod\", 8.2));\n    }\n\n    @Test\n    public void testInvokePrivateMethod_primtiveType_withoutSpecifyingMethodName() throws Exception {\n        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.4d));\n    }\n\n    /**\n     * This test actually invokes the <code>finalize</code> method of\n     * <code>java.lang.Object</code> because we supply no method name and no\n     * arguments. <code>finalize</code> is thus the first method found and it'll\n     * be executed.\n     *\n     * @throws Exception\n     */\n    @Test\n    @Ignore(\"Invokes different methods on PC and MAC (hashCode on mac)\")\n    public void testInvokePrivateMethod_withoutSpecifyingMethodName_noArguments() throws Exception {\n        assertNull(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods()));\n    }\n\n    @Test\n    public void testInvokePrivateMethod_withoutSpecifyingMethodName_assertThatNullWorks() throws Exception {\n        assertTrue(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.3d, null) instanceof Object);\n    }\n\n    /**\n     * This test should actually fail since equals takes an Object and we pass\n     * in a primitive wrapped as a Double. Thus PowerMock cannot determine\n     * whether to invoke the single argument method defined in\n     * {@link ClassWithUniquePrivateMethods} or the\n     * {@link Object#equals(Object)} method because we could potentially invoke\n     * equals with a Double.\n     */\n    @Test(expected = TooManyMethodsFoundException.class)\n    public void testInvokePrivateMethod_withoutSpecifyingMethodName_onlyOneArgument() throws Exception {\n        Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d);\n    }\n\n    @Test(expected = TooManyMethodsFoundException.class)\n    public void testInvokeStaticPrivateMethod_withoutSpecifyingMethodName_onlyOneArgument() throws Exception {\n        assertTrue((Boolean) Whitebox.invokeMethod(ClassWithUniquePrivateMethods.class, 8.2d));\n    }\n\n    @Test\n    public void testInvokePrivateMethod_primtiveType_Wrapped() throws Exception {\n        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), \"primitiveMethod\", new Double(8.2)));\n    }\n\n    @Test\n    public void testInvokePrivateMethod_wrappedType() throws Exception {\n        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), \"wrappedMethod\", new Double(8.2)));\n    }\n\n    @Test\n    public void testInvokePrivateMethod_wrappedType_primitive() throws Exception {\n        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), \"wrappedMethod\", 8.2));\n    }\n\n    @Test\n    public void testMethodWithPrimitiveIntAndString_primitive() throws Exception {\n        assertEquals(\"My int value is: \" + 8, Whitebox.invokeMethod(new ClassWithPrivateMethods(),\n                                                                    \"methodWithPrimitiveIntAndString\", 8, \"My int value is: \"));\n    }\n\n    @Test\n    public void testMethodWithPrimitiveIntAndString_Wrapped() throws Exception {\n        assertEquals(\"My int value is: \" + 8, Whitebox.invokeMethod(new ClassWithPrivateMethods(),\n                                                                    \"methodWithPrimitiveIntAndString\", Integer.valueOf(8), \"My int value is: \"));\n    }\n\n    @Test\n    public void testMethodWithPrimitiveAndWrappedInt_primtive_wrapped() throws Exception {\n        assertEquals(17, Whitebox.invokeMethod(new ClassWithPrivateMethods(), \"methodWithPrimitiveAndWrappedInt\",\n                                               new Class[]{int.class, Integer.class}, 9, Integer.valueOf(8)));\n    }\n\n    @Test\n    public void testStaticState() {\n        int expected = 123;\n        Whitebox.setInternalState(ClassWithInternalState.class, \"staticState\", expected);\n        assertEquals(expected, ClassWithInternalState.getStaticState());\n        assertEquals(expected, Whitebox.getInternalState(ClassWithInternalState.class, \"staticState\"));\n    }\n\n\t@Test\n\tpublic void testStaticFinalPrimitiveState() {\n\t\tWhitebox.setInternalState(ClassWithInternalState.class, \"staticFinalIntState\", 123);\n                assertEquals(123, Whitebox.getInternalState(ClassWithInternalState.class, \"staticFinalIntState\"));\n\t}\n\n\t@Test\n\tpublic void testStaticFinalStringState() throws NoSuchFieldException {\n\t\tWhitebox.setInternalState(ClassWithInternalState.class, \"staticFinalStringState\", \"Brand new string\");\n                assertEquals(\"Brand new string\", Whitebox.getInternalState(ClassWithInternalState.class, \"staticFinalStringState\"));\n\t}\n\n\t@Test\n\tpublic void testStaticFinalObject() throws NoSuchFieldException {\n\t\tint modifiersBeforeSet = ClassWithInternalState.class.getDeclaredField(\"staticFinalIntegerState\").getModifiers();\n\t\tInteger newValue = ClassWithInternalState.getStaticFinalIntegerState() + 1;\n\n\t\tWhitebox.setInternalState(ClassWithInternalState.class, \"staticFinalIntegerState\", newValue);\n\n\t\tint modifiersAfterSet = ClassWithInternalState.class.getDeclaredField(\"staticFinalIntegerState\").getModifiers();\n\t\tassertEquals(newValue, ClassWithInternalState.getStaticFinalIntegerState());\n\t\tassertEquals(modifiersBeforeSet, modifiersAfterSet);\n\t}\n\n    /**\n     * Verifies that the http://code.google.com/p/powermock/issues/detail?id=6\n     * is fixed.\n     */\n    @Test(expected = IllegalArgumentException.class)\n    public void testInvokeMethodWithNullParameter() throws Exception {\n        Whitebox.invokeMethod(null, \"method\");\n    }\n\n    @Test(expected = IllegalArgumentException.class)\n    public void testInvokeConstructorWithNullParameter() throws Exception {\n        Whitebox.invokeConstructor(null, \"constructor\");\n    }\n\n    @Test(expected = IllegalArgumentException.class)\n    public void testGetInternalWithNullParameter() throws Exception {\n        Whitebox.getInternalState(null, \"state\");\n    }\n\n    @Test(expected = IllegalArgumentException.class)\n    public void testSetInternalWithNullParameter() throws Exception {\n        Whitebox.setInternalState(null, \"state\", new Object());\n    }\n\n    @Test\n    public void testInstantiateVarArgsOnlyConstructor() throws Exception {\n        final String argument1 = \"argument1\";\n        final String argument2 = \"argument2\";\n        ClassWithVarArgsConstructor instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor.class, argument1,\n                                                                          argument2);\n        String[] strings = instance.getStrings();\n        assertEquals(2, strings.length);\n        assertEquals(argument1, strings[0]);\n        assertEquals(argument2, strings[1]);\n    }\n\n    @Test\n    public void testInstantiateVarArgsOnlyConstructor_noArguments() throws Exception {\n        ClassWithVarArgsConstructor instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor.class);\n        String[] strings = instance.getStrings();\n        assertEquals(0, strings.length);\n    }\n\n    @Test\n    public void testInvokeVarArgsMethod_multipleValues() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        assertEquals(6, Whitebox.invokeMethod(tested, \"varArgsMethod\", 1, 2, 3));\n    }\n\n    @Test\n    public void testInvokeVarArgsMethod_noArguments() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        assertEquals(0, Whitebox.invokeMethod(tested, \"varArgsMethod\"));\n    }\n\n    @Test\n    public void testInvokeVarArgsMethod_oneArgument() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        assertEquals(4, Whitebox.invokeMethod(tested, \"varArgsMethod\", 2));\n    }\n\n    @Test\n    public void testInvokeVarArgsMethod_invokeVarArgsWithOneArgument() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        assertEquals(1, Whitebox.invokeMethod(tested, \"varArgsMethod\", new Class<?>[]{int[].class}, 1));\n    }\n\n    @Test\n    public void testInvokePrivateMethodWithASubTypeOfTheArgumentType() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        ClassWithChildThatHasInternalState argument = new ClassWithChildThatHasInternalState();\n        assertSame(argument, Whitebox.invokeMethod(tested, \"methodWithObjectArgument\", argument));\n    }\n\n    @Test\n    public void testInvokePrivateMethodWithAClassArgument() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        assertEquals(ClassWithChildThatHasInternalState.class, Whitebox.invokeMethod(tested, \"methodWithClassArgument\",\n                                                                                     ClassWithChildThatHasInternalState.class));\n    }\n\n    @Test\n    public void testSetInternalStateInChildClassWithoutSpecifyingTheChildClass() throws Exception {\n        final int value = 22;\n        final String fieldName = \"internalState\";\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {\n        };\n        Whitebox.setInternalState(tested, fieldName, value);\n        assertEquals(value, Whitebox.getInternalState(tested, fieldName));\n    }\n\n    @Test\n    public void testSetInternalStateInClassAndMakeSureThatTheChildClassIsNotAffectedEvenThoughItHasAFieldWithTheSameName()\n            throws Exception {\n        final int value = 22;\n        final String fieldName = \"anotherInternalState\";\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {\n        };\n        Whitebox.setInternalState(tested, fieldName, value);\n        assertEquals(value, Whitebox.getInternalState(tested, fieldName));\n        assertEquals(-1, Whitebox.getInternalState(tested, fieldName, ClassWithInternalState.class));\n    }\n\n    @Test(expected = IllegalArgumentException.class)\n    public void testSetInternalStateWithInvalidArgumentType() throws Exception {\n        final int value = 22;\n        final String fieldName = \"internalState\";\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {\n        };\n        Whitebox.setInternalState(tested, fieldName, new Object());\n        assertEquals(value, Whitebox.getInternalState(tested, fieldName));\n    }\n\n    @Test(expected = IllegalArgumentException.class)\n    public void testSetInternalStateWithNull() throws Exception {\n        final int value = 22;\n        final String fieldName = \"internalState\";\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {\n        };\n        Whitebox.setInternalState(tested, fieldName, (Object) null);\n        assertEquals(value, Whitebox.getInternalState(tested, fieldName));\n    }\n\n    @Test\n    public void testSetAndGetInternalStateBasedOnFieldType() throws Exception {\n        final int value = 22;\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, int.class, value);\n        assertEquals(value, (int) Whitebox.getInternalState(tested, int.class));\n        assertEquals(value, Whitebox.getInternalState(tested, \"anotherInternalState\"));\n        assertEquals(value, Whitebox.getInternalState(tested, \"anotherInternalState\",\n                                                      ClassWithChildThatHasInternalState.class));\n    }\n\n    @Test\n    public void testSetAndGetInternalStateAtASpecificPlaceInTheHierarchyBasedOnFieldType() throws Exception {\n        final int value = 22;\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, int.class, value, ClassWithInternalState.class);\n        assertEquals(42, (int) Whitebox.getInternalState(tested, int.class));\n        assertEquals(value, (int) Whitebox.getInternalState(tested, int.class, ClassWithInternalState.class));\n        assertEquals(value, Whitebox.getInternalState(tested, \"staticState\", ClassWithInternalState.class));\n    }\n\n    @Test\n    public void testSetInternalStateBasedOnObjectType() throws Exception {\n        final String value = \"a string\";\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, value);\n        assertEquals(value, Whitebox.getInternalState(tested, String.class));\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    @Test\n    public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveType() throws Exception {\n        final int value = 22;\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, value);\n        assertEquals((Integer) value, Whitebox.getInternalState(tested, \"anotherInternalState\",\n                                                                ClassWithChildThatHasInternalState.class, Integer.class));\n    }\n\n    @Test\n    public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveTypeUsingGenerics() throws Exception {\n        final int value = 22;\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, value);\n        assertEquals((Integer) value, Whitebox.<Integer>getInternalState(tested, \"anotherInternalState\",\n                                                                         ClassWithChildThatHasInternalState.class));\n    }\n\n    @Test\n    public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchy() throws Exception {\n        final String value = \"a string\";\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, (Object) value, ClassWithInternalState.class);\n        assertEquals(value, Whitebox.getInternalState(tested, \"finalString\"));\n    }\n\n    @Test\n    public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchyForPrimitiveType()\n            throws Exception {\n        final long value = 31;\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, value, ClassWithInternalState.class);\n        assertEquals(value, tested.getInternalLongState());\n    }\n\n    @Test\n    public void testSetInternalStateBasedOnObjectTypeAtANonSpecificPlaceInTheClassHierarchyForPrimitiveType()\n            throws Exception {\n        final long value = 31;\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, value);\n        assertEquals(value, tested.getInternalLongState());\n    }\n\n    @Test\n    public void testSetInternalMultipleOfSameTypeOnSpecificPlaceInHierarchy() throws Exception {\n        final int value = 31;\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        try {\n            Whitebox.setInternalState(tested, value, ClassWithInternalState.class);\n            fail(\"should throw TooManyFieldsFoundException!\");\n        } catch (TooManyFieldsFoundException e) {\n            assertEquals(\"Two or more fields matching type int.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSetInternalMultipleOfSameType() throws Exception {\n        final int value = 31;\n        ClassWithInternalState tested = new ClassWithInternalState();\n        try {\n            Whitebox.setInternalState(tested, value);\n            fail(\"should throw TooManyFieldsFoundException!\");\n        } catch (TooManyFieldsFoundException e) {\n            assertEquals(\"Two or more fields matching type int.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSetInternalStateBasedOnObjectSubClassTypeAtASpecificPlaceInTheClassHierarchy() throws Exception {\n        final ClassWithPrivateMethods value = new ClassWithPrivateMethods() {\n        };\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();\n        Whitebox.setInternalState(tested, value, ClassWithInternalState.class);\n        assertSame(value, tested.getClassWithPrivateMethods());\n    }\n\n    @Test\n    public void testSetInternalStateBasedOnObjectSubClassType() throws Exception {\n        final ClassWithPrivateMethods value = new ClassWithPrivateMethods() {\n        };\n        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {\n        };\n        Whitebox.setInternalState(tested, value);\n        assertSame(value, tested.getClassWithPrivateMethods());\n    }\n\n    @Test\n    public void testGetAllInstanceFields() throws Exception {\n        Set<Field> allFields = Whitebox.getAllInstanceFields(new ClassWithChildThatHasInternalState());\n        assertEquals(8, allFields.size());\n    }\n\n    @Test\n    public void testGetAllInstanceFieldsOnClass() {\n        Set<Field> allFields = Whitebox.getAllInstanceFields(ClassWithChildThatHasInternalState.class);\n        assertEquals(8, allFields.size());\n    }\n\n    @Test\n    public void testGetAllStaticFields_assertNoFieldsFromParent() throws Exception {\n        Set<Field> allFields = Whitebox.getAllStaticFields(ClassWithChildThatHasInternalState.class);\n        assertEquals(0, allFields.size());\n    }\n\n\t@Test\n\tpublic void testGetAllStaticFields() throws Exception {\n\t\tSet<Field> allFields = Whitebox.getAllStaticFields(ClassWithInternalState.class);\n\t\tassertEquals(4, allFields.size());\n\t}\n\n    @Test\n    public void testMethodWithNoMethodName_noMethodFound() throws Exception {\n        try {\n            Whitebox.getMethod(ClassWithInternalState.class, int.class);\n            fail(\"Should throw MethodNotFoundException\");\n        } catch (MethodNotFoundException e) {\n            assertEquals(\n                    \"No method was found with parameter types: [ int ] in class org.powermock.reflect.testclasses.ClassWithInternalState.\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void testMethodWithNoMethodName_tooManyMethodsFound() throws Exception {\n        try {\n            Whitebox.getMethod(ClassWithSeveralMethodsWithSameName.class);\n            fail(\"Should throw TooManyMethodsFoundException\");\n        } catch (TooManyMethodsFoundException e) {\n            assertTrue(e\n                               .getMessage()\n                               .contains(\n                                       \"Several matching methods found, please specify the method name so that PowerMock can determine which method you're referring to\"));\n        }\n    }\n\n    @Test\n    public void testMethodWithNoMethodName_ok() throws Exception {\n        final Method method = Whitebox.getMethod(ClassWithSeveralMethodsWithSameName.class, double.class);\n        assertEquals(method, ClassWithSeveralMethodsWithSameName.class.getDeclaredMethod(\"getDouble\", double.class));\n    }\n\n    @Test\n    public void testGetTwoMethodsWhenNoneOfThemAreFound() throws Exception {\n        try {\n            Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, \"notFound1\", \"notFound2\");\n        } catch (MethodNotFoundException e) {\n            assertEquals(\n                    \"No methods matching the name(s) notFound1 or notFound2 were found in the class hierarchy of class org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName.\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void testGetThreeMethodsWhenNoneOfThemAreFound() throws Exception {\n        try {\n            Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, \"notFound1\", \"notFound2\", \"notFound3\");\n        } catch (MethodNotFoundException e) {\n            assertEquals(\n                    \"No methods matching the name(s) notFound1, notFound2 or notFound3 were found in the class hierarchy of class org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName.\",\n                    e.getMessage());\n        }\n    }\n\n    /**\n     * Asserts that <a\n     * href=\"http://code.google.com/p/powermock/issues/detail?id=118\">issue\n     * 118</a> is fixed. Thanks to cemcatik for finding this.\n     */\n    @Test\n    public void testInvokeConstructorWithBothNormalAndVarArgsParameter() throws Exception {\n        ClassWithVarArgsConstructor2 instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor2.class, \"first\",\n                                                                           \"second\", \"third\");\n        assertArrayEquals(new String[]{\"first\", \"second\", \"third\"}, instance.getStrings());\n    }\n\n    /**\n     * Asserts that <a\n     * href=\"http://code.google.com/p/powermock/issues/detail?id=118\">issue\n     * 118</a> is fixed. Thanks to cemcatik for finding this.\n     */\n    @Test\n    public void testInvokeMethodWithBothNormalAndVarArgsParameter() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        assertEquals(4, Whitebox.invokeMethod(tested, \"varArgsMethod2\", 1, 2, 3));\n    }\n\n    @Test\n    public void testInvokePrivateMethodWithArrayArgument() throws Exception {\n        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();\n        assertEquals(\"Hello World\", Whitebox.invokeMethod(tested, \"evilConcatOfStrings\", new Object[]{new String[]{\n                \"Hello \", \"World\"}}));\n    }\n\n    @Test\n    public void testSetInternalStateFromContext_allStatesInSameOneContext() throws Exception {\n        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();\n        MyContext context = new MyContext();\n        Whitebox.setInternalStateFromContext(tested, context);\n        assertEquals(context.getMyStringState(), tested.getSomeStringState());\n        assertEquals(context.getMyIntState(), tested.getSomeIntState());\n    }\n\n    @Test\n    public void testSetInternalStateFromContext_statesInDifferentContext() throws Exception {\n        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();\n        MyIntContext myIntContext = new MyIntContext();\n        MyStringContext myStringContext = new MyStringContext();\n        Whitebox.setInternalStateFromContext(tested, myIntContext, myStringContext);\n        assertEquals(myStringContext.getMyStringState(), tested.getSomeStringState());\n        assertEquals(myIntContext.getSimpleIntState(), tested.getSomeIntState());\n    }\n\n    @Test\n    public void testSetInternalStateFromContext_contextIsAClass() throws Exception {\n        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();\n        Whitebox.setInternalStateFromContext(tested, MyContext.class);\n        assertEquals(Whitebox.getInternalState(MyContext.class, long.class), (Long) tested.getSomeStaticLongState());\n    }\n\n    @Test\n    public void testSetInternalStateFromContext_contextIsAClassAndAnInstance() throws Exception {\n        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();\n        MyContext myContext = new MyContext();\n        Whitebox.setInternalStateFromContext(tested, MyContext.class, myContext);\n        assertEquals(myContext.getMyStringState(), tested.getSomeStringState());\n        assertEquals(myContext.getMyIntState(), tested.getSomeIntState());\n        assertEquals((Long) myContext.getMyLongState(), (Long) tested.getSomeStaticLongState());\n    }\n\n    @Test\n    public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyInstanceContext()\n            throws Exception {\n        ClassWithStaticAndInstanceInternalStateOfSameType.reset();\n        ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType();\n        OneInstanceAndOneStaticFieldOfSameTypeContext context = new OneInstanceAndOneStaticFieldOfSameTypeContext();\n        Whitebox.setInternalStateFromContext(tested, context);\n        assertEquals(context.getMyStringState(), tested.getStringState());\n        assertEquals(\"Static String state\", tested.getStaticStringState());\n    }\n\n    @Test\n    public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyStaticContext()\n            throws Exception {\n        ClassWithStaticAndInstanceInternalStateOfSameType.reset();\n        ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType();\n        Whitebox.setInternalStateFromContext(tested, OneInstanceAndOneStaticFieldOfSameTypeContext.class);\n        assertEquals(OneInstanceAndOneStaticFieldOfSameTypeContext.getMyStaticStringState(), tested\n                                                                                                     .getStaticStringState());\n        assertEquals(\"String state\", tested.getStringState());\n    }\n\n    @Test\n    public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectByDefault()\n            throws Exception {\n        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();\n        InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext();\n        assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString());\n\n        Whitebox.setInternalStateFromContext(tested, fieldsNotInTargetContext);\n        assertEquals(tested.getSomeStringState(), fieldsNotInTargetContext.getString());\n    }\n\n    @Test\n    public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy()\n            throws Exception {\n        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();\n        InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext();\n        assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString());\n        Whitebox.setInternalStateFromContext(tested, fieldsNotInTargetContext, FieldMatchingStrategy.MATCHING);\n        assertEquals(tested.getSomeStringState(), fieldsNotInTargetContext.getString());\n    }\n\n    @Test(expected = FieldNotFoundException.class)\n    public void setInternalStateFromInstanceContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy()\n            throws Exception {\n        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();\n        InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext();\n        assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString());\n        Whitebox.setInternalStateFromContext(tested, fieldsNotInTargetContext, FieldMatchingStrategy.STRICT);\n        assertEquals(tested.getSomeStringState(), fieldsNotInTargetContext.getString());\n    }\n\n    @Test\n    public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectByDefault() throws Exception {\n        long state = ClassWithSimpleInternalState.getLong();\n        try {\n            assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong());\n            Whitebox.setInternalStateFromContext(ClassWithSimpleInternalState.class,\n                                                 ClassFieldsNotInTargetContext.class);\n            assertEquals(ClassFieldsNotInTargetContext.getLong(), ClassWithSimpleInternalState.getLong());\n        } finally {\n            // Restore the state\n            ClassWithSimpleInternalState.setLong(state);\n        }\n    }\n\n    @Test\n    public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy()\n            throws Exception {\n        long state = ClassWithSimpleInternalState.getLong();\n        try {\n            assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong());\n            Whitebox.setInternalStateFromContext(ClassWithSimpleInternalState.class,\n                                                 ClassFieldsNotInTargetContext.class, FieldMatchingStrategy.MATCHING);\n            assertEquals(ClassFieldsNotInTargetContext.getLong(), ClassWithSimpleInternalState.getLong());\n        } finally {\n            // Restore the state\n            ClassWithSimpleInternalState.setLong(state);\n        }\n    }\n\n    @Test(expected = FieldNotFoundException.class)\n    public void setInternalStateFromClassContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy()\n            throws Exception {\n        long state = ClassWithSimpleInternalState.getLong();\n        try {\n            assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong());\n            Whitebox.setInternalStateFromContext(ClassWithSimpleInternalState.class,\n                                                 ClassFieldsNotInTargetContext.class, FieldMatchingStrategy.STRICT);\n        } finally {\n            // Restore the state\n            ClassWithSimpleInternalState.setLong(state);\n        }\n    }\n\n    @Test\n    public void assertThatErrorMessageIsCorrectWhenNoInstanceFieldFound() throws Exception {\n        ClassWithInternalState classWithInternalState = new ClassWithInternalState();\n        try {\n            Whitebox.setInternalState(classWithInternalState, (byte) 23);\n            fail(\"Should throw a FieldNotFoundException.\");\n        } catch (FieldNotFoundException e) {\n            assertEquals(\n                    \"No instance field assignable from \\\"java.lang.Byte\\\" could be found in the class hierarchy of \"\n                            + ClassWithInternalState.class.getName() + \".\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void assertThatErrorMessageIsCorrectWhenNoStaticFieldFound() throws Exception {\n        try {\n            Whitebox.setInternalState(ClassWithInternalState.class, (byte) 23);\n            fail(\"Should throw a FieldNotFoundException.\");\n        } catch (FieldNotFoundException e) {\n            assertEquals(\"No static field assignable from \\\"java.lang.Byte\\\" could be found in the class hierarchy of \"\n                                 + ClassWithInternalState.class.getName() + \".\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void assertThatWhiteboxWorksWithGenericsWhenSpecifyingFieldName() throws Exception {\n        ClassWithInternalState object = new ClassWithInternalState();\n        Set<String> state = Whitebox.getInternalState(object, \"genericState\");\n        assertSame(object.getGenericState(), state);\n    }\n\n    @Test\n    public void whiteboxGetMethodWithCorrectMethodNameButWrongParameterTypeReturnsErrorMessageReflectingTheWrongParameter()\n            throws Exception {\n        try {\n            Whitebox.getMethod(ClassWithInternalState.class, \"methodWithArgument\", String.class, InputStream.class);\n            fail(\"Should throw MethodNotFoundException\");\n        } catch (MethodNotFoundException e) {\n            assertEquals(\n                    \"No method found with name 'methodWithArgument' with parameter types: [ java.lang.String, java.io.InputStream ] in class org.powermock.reflect.testclasses.ClassWithInternalState.\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void whiteboxSetInternalStateWorksOnArraysWhenDefiningMethodName() {\n        ClassWithInternalState tested = new ClassWithInternalState();\n        final String[] expected = new String[]{\"string1\", \"string2\"};\n        Whitebox.setInternalState(tested, \"stringArray\", expected);\n        assertArrayEquals(expected, tested.getStringArray());\n    }\n\n    @Test\n    public void whiteboxSetInternalStateWorksOnArraysWhenNotDefiningMethodName() {\n        ClassWithInternalState tested = new ClassWithInternalState();\n        final String[] expected = new String[]{\"string1\", \"string2\"};\n        Whitebox.setInternalState(tested, expected);\n        assertArrayEquals(expected, tested.getStringArray());\n    }\n\n    @Test\n    public void getInternalStateThrowsIAEWhenInstanceIsNull() {\n        try {\n            Whitebox.getInternalState(null, String.class);\n            fail(\"Should throw IllegalArgumentException\");\n        } catch (IllegalArgumentException e) {\n            assertEquals(\"The object containing the field cannot be null\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void getInternalStateSupportsObjectArrayWhenSUTContainsSerializable() {\n        ClassWithSerializableState tested = new ClassWithSerializableState();\n        tested.setSerializable(new Serializable() {\n            private static final long serialVersionUID = -1850246005852779087L;\n        });\n        tested.setObjectArray(new Object[0]);\n        assertNotNull(Whitebox.getInternalState(tested, Object[].class));\n    }\n\n    @Test\n    public void getInternalStateUsesAssignableToWhenLookingForObject() {\n        ClassWithList tested = new ClassWithList();\n        assertNotNull(Whitebox.getInternalState(tested, Object.class));\n    }\n\n    @Test(expected = TooManyFieldsFoundException.class)\n    public void getInternalStateThrowsTooManyFieldsFoundWhenTooManyFieldsMatchTheSuppliedType() {\n        ClassWithInternalState tested = new ClassWithInternalState();\n        assertNotNull(Whitebox.getInternalState(tested, Object.class));\n    }\n\n    @Test\n    public void invokeMethodInvokesOverridenMethods() throws Exception {\n        assertTrue(Whitebox.<Boolean>invokeMethod(new ClassWithOverriddenMethod(), 2.0d));\n    }\n\n    @Test(expected = IllegalArgumentException.class)\n    public void newInstanceThrowsIAEWhenClassIsAbstract() throws Exception {\n        Whitebox.newInstance(AbstractClass.class);\n    }\n\n    @Test\n    public void newInstanceReturnsJavaProxyWhenInterface() throws Exception {\n        AnInterface instance = Whitebox.newInstance(AnInterface.class);\n        assertTrue(Proxy.isProxyClass(instance.getClass()));\n    }\n\n    @Test\n    public void newInstanceCreatesAnEmptyArrayWhenClassIsArray() throws Exception {\n        byte[] newInstance = Whitebox.newInstance(byte[].class);\n        assertEquals(0, newInstance.length);\n    }\n\n    @Test(expected = IllegalArgumentException.class)\n    public void invokeMethodSupportsNullParameters() throws Exception {\n        ClassWithAMethod classWithAMethod = new ClassWithAMethod();\n        Connection connection = null;\n        Whitebox.invokeMethod(classWithAMethod, \"connect\", connection);\n    }\n\n    @Test(expected = MethodNotFoundException.class)\n    public void invokeOverriddenMethodWithNullParameterThrowsIAE() throws Exception {\n        ClassWithOverloadedMethods tested = new ClassWithOverloadedMethods();\n        Child child = null;\n        Whitebox.invokeMethod(tested, \"overloaded\", 2, child);\n    }\n\n    @Test\n    public void canPassNullParamToPrivateStaticMethod() throws Exception {\n        assertEquals(\"hello\", Whitebox.invokeMethod(ClassWithStaticMethod.class, \"aStaticMethod\", (Object[])null));\n    }\n\n    @Test\n    public void canPassNullParamToPrivateStaticMethodWhenDefiningParameterTypes() throws Exception {\n        assertEquals(\"hello\", Whitebox.invokeMethod(ClassWithStaticMethod.class, \"aStaticMethod\", new Class<?>[]{byte[].class}, (Object[])null));\n    }\n\n    @Test\n    public void canPassNullPrimitiveArraysToAPrivateStaticMethod() throws Exception {\n        assertEquals(\"hello\", Whitebox.invokeMethod(ClassWithStaticMethod.class, \"aStaticMethod\", (byte[]) null));\n    }\n\n    @Test\n    public void canPassMultipleNullValuesToStaticMethod() throws Exception {\n        assertEquals(\"null null\", Whitebox.invokeMethod(ClassWithStaticMethod.class, \"anotherStaticMethod\", (Object) null, (byte[]) null));\n    }\n\n\n    @Test\n    public void testObjectConstructors() throws Exception {\n        String name = \"objectConstructor\";\n        ClassWithObjectConstructors instance = Whitebox.invokeConstructor(ClassWithObjectConstructors.class,\n                                                                          name);\n\n        assertEquals(instance.getName(), name);\n    }\n\n    @Test\n    public void testInterfaceConstructors() throws Exception {\n        ConstructorInterface param = new ConstructorInterfaceImpl(\"constructorInterfaceSomeValue\");\n        ClassWithInterfaceConstructors instance = Whitebox.invokeConstructor(ClassWithInterfaceConstructors.class,\n                                                                             param);\n\n        assertEquals(instance.getValue(), param.getValue());\n    }\n\n    @Test\n    public void testPrimitiveConstructorsArgumentBoxed() throws Exception {\n        Long arg = 1L;\n        ClassWithPrimitiveConstructors instance = Whitebox.invokeConstructor(ClassWithPrimitiveConstructors.class,\n                                                                             arg);\n\n        assertEquals(instance.getValue(), arg.longValue());\n    }\n\n    @Test\n    public void testOverloadedConstructors() throws Exception {\n        String name = \"overloadedConstructor\";\n        ClassWithOverloadedConstructors instance = Whitebox.invokeConstructor(ClassWithOverloadedConstructors.class,\n                                                                              true, name);\n\n        assertEquals(instance.getName(), name);\n        assertTrue(instance.isBool());\n\n        assertThat(instance.isBool1()).isFalse();\n    }\n\n    @Test\n    @Ignore(\"Reflection and direct call returns different values.\")\n    public void testFinalState() {\n        ClassWithInternalState state = new ClassWithInternalState();\n        String expected = \"changed\";\n        Whitebox.setInternalState(state, \"finalString\", expected);\n        assertEquals(expected, state.getFinalString());\n        assertEquals(expected, Whitebox.getInternalState(state, \"finalString\"));\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/context/ClassFieldsNotInTargetContext.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.context;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The purpose of this context is that it should define fields not available in\n * the target object to where the state is supposed to be copied.\n */\npublic class ClassFieldsNotInTargetContext {\n\tprivate static long something = 42L;\n\n\tprivate static Map<?, ?> map = new HashMap<Object, Object>();\n\n\tpublic static long getLong() {\n\t\treturn something;\n\t}\n\n\tpublic static Map<?, ?> getMap() {\n\t\treturn map;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/context/InstanceFieldsNotInTargetContext.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.context;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The purpose of this context is that it should define fields not available in\n * the target object to where the state is supposed to be copied.\n */\npublic class InstanceFieldsNotInTargetContext {\n\tprivate String something = \"something\";\n\n\tprivate Map<?, ?> map = new HashMap<Object, Object>();\n\n\tpublic String getString() {\n\t\treturn something;\n\t}\n\n\tpublic Map<?, ?> getMap() {\n\t\treturn map;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/context/MyContext.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.context;\n\npublic class MyContext {\n    private int myIntState = 42;\n\n    private String myStringState = \"myString\";\n\n    private static long myLongState = 21L;\n\n    public long getMyLongState() {\n        return myLongState;\n    }\n\n    public int getMyIntState() {\n        return myIntState;\n    }\n\n    public String getMyStringState() {\n        return myStringState;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/context/MyIntContext.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.context;\n\npublic class MyIntContext {\n    \n    private int simpleIntState = 42;\n\n    public int getSimpleIntState() {\n        return simpleIntState;\n    }\n}\n\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/context/MyStringContext.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.context;\n\npublic class MyStringContext {\n    private String myStringState = \"string\";\n\n    public String getMyStringState() {\n        return myStringState;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/context/OneInstanceAndOneStaticFieldOfSameTypeContext.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.context;\n\npublic class OneInstanceAndOneStaticFieldOfSameTypeContext {\n\n    private String myStringState = \"myString\";\n\n    private static String myStaticStringState = \"21L\";\n\n    public String getMyStringState() {\n        return myStringState;\n    }\n\n    public static String getMyStaticStringState() {\n        return myStaticStringState;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/internal/WhiteboxImplTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.internal;\n\nimport org.junit.Test;\nimport org.powermock.reflect.testclasses.*;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assume.assumeTrue;\n\n\n/**\n * Unit tests specific to the WhiteboxImpl.\n */\npublic class WhiteboxImplTest {\n\n\t/**\n\t * Asserts that a previous bug was fixed.\n\t */\n\t@Test\n\tpublic void assertThatClassAndNotStringIsNotSameWhenInvokingCheckIfTypesAreSame() throws Exception {\n\t\tMethod method = WhiteboxImpl.getMethod(WhiteboxImpl.class, \"checkIfParameterTypesAreSame\", boolean.class,\n\t\t\t\tClass[].class, Class[].class);\n\t\tboolean invokeMethod = (Boolean) method.invoke(WhiteboxImpl.class, false, new Class<?>[] { Class.class },\n\t\t\t\tnew Class<?>[] { String.class });\n\t\tassertThat(invokeMethod).isFalse();\n\t}\n\n\t@Test\n\tpublic void assertThatClassAndClassIsSameWhenInvokingCheckIfTypesAreSame() throws Exception {\n\t\tMethod method = WhiteboxImpl.getMethod(WhiteboxImpl.class, \"checkIfParameterTypesAreSame\", boolean.class,\n\t\t\t\tClass[].class, Class[].class);\n\t\tboolean invokeMethod = (Boolean) method.invoke(WhiteboxImpl.class, false, new Class<?>[] { Class.class },\n\t\t\t\tnew Class<?>[] { Class.class });\n\t\tassertThat(invokeMethod).isTrue();\n\t}\n\n\t@Test\n\tpublic void getBestCandidateMethodReturnsMatchingMethodWhenNoOverloading() throws Exception {\n\t\tfinal Method expectedMethod = ClassWithStandardMethod.class.getDeclaredMethod(\"myMethod\", double.class);\n\t\tfinal Method actualMethod = WhiteboxImpl.getBestMethodCandidate(ClassWithStandardMethod.class, \"myMethod\",\n\t\t\t\tnew Class<?>[] { double.class }, false);\n\t\tassertThat(actualMethod).isEqualTo(expectedMethod);\n\t}\n\n\t@Test\n\tpublic void getBestCandidateMethodReturnsMatchingMethodWhenOverloading() throws Exception {\n\t\tfinal Method expectedMethod = ClassWithOverloadedMethods.class.getDeclaredMethod(\"overloaded\", double.class,\n\t\t\t\tChild.class);\n\t\tfinal Method actualMethod = WhiteboxImpl.getBestMethodCandidate(ClassWithOverloadedMethods.class, \"overloaded\",\n\t\t\t\tnew Class<?>[] { double.class, Child.class }, false);\n\t\tassertThat(actualMethod).isEqualTo(expectedMethod);\n\t}\n\n    @Test\n    public void defaultMethodsAreFound() throws Exception {\n        assumeTrue(Float.valueOf(System.getProperty(\"java.specification.version\")) >= 1.8f);\n\n        Method[] methods = WhiteboxImpl.getAllMethods(Collection.class);\n        List<String> methodNames = new ArrayList<String>();\n        for (Method method : methods) {\n            methodNames.add(method.getName());\n        }\n\n        assertThat(methodNames).contains(\"stream\");\n    }\n\n    @Test\n\tpublic void testGetMethodNotExactParameterTypeMatch() throws NoSuchMethodException {\n\t\tMethod[] methods =\n\t\t\tWhiteboxImpl.getMethods(\n\t\t\t\tClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments.class,\n\t\t\t\t\"methodHavingBothPrimitiveTypeAndWrappedTypeArguments\",\n\t\t\t\tnew Class<?>[]{Integer.class, Integer.class},\n\t\t\t\tfalse\n\t\t\t);\n\t\tMethod method = ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments.class.getMethod(\n\t\t\t\t\"methodHavingBothPrimitiveTypeAndWrappedTypeArguments\",\n\t\t\t\tInteger.class,\n\t\t\t\tint.class\n\t\t);\n\t\tassertEquals(methods[0], method);\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/AnotherInterface.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\npublic interface AnotherInterface {\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ClassFactory.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\nimport net.bytebuddy.jar.asm.ClassWriter;\nimport net.bytebuddy.jar.asm.MethodVisitor;\nimport net.bytebuddy.jar.asm.Opcodes;\n\nclass ClassFactory implements Opcodes {\n    \n    static byte[] create(String className) throws Exception {\n        \n        ClassWriter cw = new ClassWriter(0);\n        MethodVisitor mv;\n        \n        cw.visit(49,\n                 ACC_PUBLIC + ACC_SUPER,\n                 className,\n                 null,\n                 \"java/lang/Object\",\n                 null);\n        \n        cw.visitSource(\"Hello.java\", null);\n        \n        {\n            mv = cw.visitMethod(ACC_PUBLIC, \"<init>\", \"()V\", null, null);\n            mv.visitVarInsn(ALOAD, 0);\n            mv.visitMethodInsn(INVOKESPECIAL,\n                               \"java/lang/Object\",\n                               \"<init>\",\n                               \"()V\", false);\n            mv.visitInsn(RETURN);\n            mv.visitMaxs(1, 1);\n            mv.visitEnd();\n        }\n        {\n            mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC,\n                                \"main\",\n                                \"([Ljava/lang/String;)V\",\n                                null,\n                                null);\n            mv.visitFieldInsn(GETSTATIC,\n                              \"java/lang/System\",\n                              \"out\",\n                              \"Ljava/io/PrintStream;\");\n            mv.visitLdcInsn(\"hello\");\n            mv.visitMethodInsn(INVOKEVIRTUAL,\n                               \"java/io/PrintStream\",\n                               \"println\",\n                               \"(Ljava/lang/String;)V\", false);\n            mv.visitInsn(RETURN);\n            mv.visitMaxs(2, 1);\n            mv.visitEnd();\n        }\n        cw.visitEnd();\n        \n        return cw.toByteArray();\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ProxyFrameworksTest.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\nimport net.sf.cglib.proxy.Enhancer;\nimport net.sf.cglib.proxy.Factory;\nimport net.sf.cglib.proxy.InvocationHandler;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.List;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class ProxyFrameworksTest {\n    \n    private ProxyFrameworks proxyFrameworks;\n    \n    @Before\n    public void setUp() throws Exception {\n        proxyFrameworks = new ProxyFrameworks();\n    }\n    \n    @Test\n    public void should_throw_illegal_argument_exception_if_class_is_null() throws Exception {\n        assertThat(proxyFrameworks.getUnproxiedType(null)).isNull();\n    }\n    \n    @Test\n    public void should_return_null_if_object_is_null() throws Exception {\n        assertThat(proxyFrameworks.getUnproxiedType((Object) null)).isNull();\n    }\n    \n    @Test\n    public void should_return_original_class_if_object_not_proxy() throws Exception {\n        SomeClass someClass = new SomeClass();\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass);\n        \n        assertThatOriginalTypeInstanceOf(unproxiedType, SomeClass.class);\n    }\n    \n    @Test\n    public void should_return_original_class_if_proxy_created_with_java() {\n        SomeInterface someInterface = createJavaProxy(new Class[]{ SomeInterface.class });\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someInterface);\n        \n        assertThatOriginalTypeInstanceOf(unproxiedType, SomeInterface.class);\n    }\n    \n    @Test\n    public void should_return_original_class_if_proxy_created_with_cglib() {\n        SomeClass someClass = (SomeClass) createCglibProxy(SomeClass.class);\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass);\n        \n        assertThatOriginalTypeInstanceOf(unproxiedType, SomeClass.class);\n    }\n    \n    @Test\n    public void should_not_detect_synthetic_classes_as_cglib_proxy() throws Exception {\n        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n        final Enumeration<URL> resources = classLoader.getResources(\"org/powermock/reflect/internal/proxy\");\n    \n        final List<URL> urls = new ArrayList<URL>();\n    \n        while (resources.hasMoreElements()) {\n            urls.add(resources.nextElement());\n        }\n        \n        String className = \"Some$$SyntheticClass$$Lambda\";\n        byte[] bytes = ClassFactory.create(className);\n        CustomClassLoader customClassLoader = new CustomClassLoader(urls.toArray(new URL[urls.size()]), classLoader);\n        \n        Class<?> defineClass = customClassLoader.defineClass(className, bytes);\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(defineClass.newInstance());\n        \n        assertThatOriginalTypeInstanceOf(unproxiedType, defineClass);\n    }\n    \n    @Test\n    public void should_return_object_as_original_class_if_no_non_no_mocking_interfaces() {\n        Factory someClass = (Factory) createCglibProxy(Factory.class);\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass);\n        \n        assertThatOriginalTypeInstanceOf(unproxiedType, Object.class);\n    }\n    \n    @Test\n    public void should_return_interface_as_original_type_if_only_one_non_mocking_interface() {\n        Factory someClass = (Factory) createCglibProxy(Factory.class, SomeInterface.class);\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass);\n        \n        assertThatOriginalTypeInstanceOf(unproxiedType, SomeInterface.class);\n    }\n    \n    @Test\n    public void should_return_interface_and_original_type_if_proxy_has_interface_and_superclass() {\n        SomeClass someClass = (SomeClass) createCglibProxy(SomeClass.class, SomeInterface.class, AnotherInterface.class);\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass);\n    \n        assertThatOriginalTypeInstanceOfAndInterfaces(unproxiedType, SomeClass.class, new Class[]{\n                SomeInterface.class,\n                AnotherInterface.class\n        });\n    }\n    \n    @Test\n    public void should_return_interfaces_if_proxy_create_from_several_interfaces() {\n        \n        Class[] interfaces = {SomeInterface.class, AnotherInterface.class};\n        \n        SomeInterface someInterface = createJavaProxy(interfaces);\n        \n        UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someInterface);\n        \n        assertThatOriginalIsNullAndInterfaces(\n                unproxiedType, interfaces\n        );\n    }\n    \n    private Object createCglibProxy(Class<?> superclass, Class... interfaces) {\n        if (interfaces.length == 0){\n            return Enhancer.create(\n                    superclass,\n                    new InvocationHandler() {\n                        @Override\n                        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {\n                            return method.invoke(o, objects);\n                        }\n                    });\n        }else {\n            return Enhancer.create(\n                    superclass,\n                    interfaces,\n                    new InvocationHandler() {\n                        @Override\n                        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {\n                            return method.invoke(o, objects);\n                        }\n                    });\n        }\n    }\n    \n    private SomeInterface createJavaProxy(Class[] interfaces) {\n        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n        return (SomeInterface) Proxy.newProxyInstance(\n                classLoader,\n                interfaces,\n                new java.lang.reflect.InvocationHandler() {\n                    @Override\n                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n                        return method.invoke(proxy, args);\n                    }\n                });\n    }\n    \n    private void assertThatOriginalIsNullAndInterfaces(UnproxiedType unproxiedType, Class[] expectedInterfaces) {\n        assertThat(unproxiedType.getOriginalType()).isNull();\n        assertThat(unproxiedType.getInterfaces())\n                .containsExactlyInAnyOrder(expectedInterfaces);\n    }\n    \n    private void assertThatOriginalTypeInstanceOf(UnproxiedType unproxiedType, Class<?> expectedClass) {\n        assertThat(unproxiedType.getOriginalType()).isEqualTo(expectedClass);\n        assertThat(unproxiedType.getInterfaces()).isEmpty();\n    }\n    \n    private void assertThatOriginalTypeInstanceOfAndInterfaces(UnproxiedType unproxiedType, Class<?> expectedClass,Class[] expectedInterfaces ) {\n        assertThat(unproxiedType.getOriginalType()).isEqualTo(expectedClass);\n        assertThat(unproxiedType.getInterfaces())\n                .containsExactlyInAnyOrder(expectedInterfaces);\n    }\n    \n    private static class CustomClassLoader extends URLClassLoader {\n    \n        private CustomClassLoader(URL[] urls, ClassLoader parent) {\n            super(urls, parent);\n        }\n        \n        Class<?> defineClass(String name, byte[] b) {\n            return defineClass(name, b, 0, b.length);\n        }\n    }\n    \n}"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/SomeClass.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\n/**\n *\n */\npublic class SomeClass {\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/SomeInterface.java",
    "content": "package org.powermock.reflect.internal.proxy;\n\npublic interface SomeInterface {\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/AbstractClass.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic abstract class AbstractClass  {\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/AnInterface.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic interface AnInterface  {\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/Child.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class Child extends Parent {\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithAMethod.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\nimport java.sql.Connection;\n\npublic class ClassWithAMethod  {\n\t\n\tpublic void connect(Connection connection) {\n\t\tif(connection == null) {\n\t\t\tthrow new IllegalArgumentException(\"param was null\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithChildThatHasInternalState.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\n@SuppressWarnings(\"unused\")\npublic class ClassWithChildThatHasInternalState extends ClassWithInternalState {\n\n\tprivate int anotherInternalState = 42;\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInterfaceConstructors.java",
    "content": "package org.powermock.reflect.testclasses;\n\n/**\n *\n */\npublic class ClassWithInterfaceConstructors {\n\n\n    private final ConstructorInterface constructorInterface;\n\n    public ClassWithInterfaceConstructors(ConstructorInterface constructorInterface) {this.constructorInterface = constructorInterface;}\n\n    public String getValue() {\n        return constructorInterface.getValue();\n    }\n\n    public interface ConstructorInterface {\n        String getValue();\n    }\n\n    public static class ConstructorInterfaceImpl implements ConstructorInterface {\n        private final String value;\n\n        public ConstructorInterfaceImpl(String value) {this.value = value;}\n\n        @Override\n        public String getValue() {\n            return value;\n        }\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInternalState.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\nimport java.io.InputStream;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class ClassWithInternalState {\n\n    private static int staticState = 5;\n\n    private static final int staticFinalIntState = 15;\n\n    private static final Integer staticFinalIntegerState = 15;\n\n    private static final String staticFinalStringState = \"Some String\";\n\n    private int internalState = 0;\n\n    private int anotherInternalState = -1;\n\n    private final String finalString = \"hello\";\n\n    private long internalLongState = 17;\n    \n\tprivate String[] stringArray = new String[0];\n\n    private Set<String> genericState = new HashSet<String>();\n\n    private ClassWithPrivateMethods classWithPrivateMethods;\n\n    public String getFinalString() {\n        return finalString;\n    }\n\n    public void increaseInteralState() {\n        internalState++;\n    }\n\n    public void decreaseInteralState() {\n        internalState--;\n    }\n\n    public int getAnotherInternalState() {\n        return anotherInternalState;\n    }\n\n    public static int getStaticState() {\n        return staticState;\n    }\n\n    public static Integer getStaticFinalIntegerState() {\n        return staticFinalIntegerState;\n    }\n\n    public ClassWithPrivateMethods getClassWithPrivateMethods() {\n        return classWithPrivateMethods;\n    }\n\n    public long getInternalLongState() {\n        return internalLongState;\n    }\n\n    public Set<String> getGenericState() {\n        return genericState;\n    }\n\n    public static String methodWithArgument(InputStream inputStream) {\n        return \"\";\n    }\n    \n    public String[] getStringArray() {\n\t\treturn stringArray;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithList.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class ClassWithList {\n\n\t@SuppressWarnings(\"unused\")\n\tprivate List<String> list = new LinkedList<String>();\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments {\n\n    public void methodHavingBothPrimitiveTypeAndWrappedTypeArguments(Integer arg0, int arg1) {\n\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithMethodUsingSuperTypeArgument.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithMethodUsingSuperTypeArgument {\n    public void methodHavingASuperTypeArgument(ClassWithStandardMethod arg) {\n\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithObjectConstructors.java",
    "content": "package org.powermock.reflect.testclasses;\n\n/**\n *\n */\npublic class ClassWithObjectConstructors {\n\n    private final Object name;\n\n    protected ClassWithObjectConstructors(Object name) {\n\n        this.name = name;\n    }\n\n    public Object getName() {\n        return name;\n    }\n\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithOverloadedConstructors.java",
    "content": "package org.powermock.reflect.testclasses;\n\n/**\n *\n */\npublic class ClassWithOverloadedConstructors {\n\n    private final String name;\n    private final boolean bool;\n    private final boolean bool1;\n\n    protected ClassWithOverloadedConstructors(String name) {\n\n        this(name, false, false);\n    }\n\n\n    protected ClassWithOverloadedConstructors(boolean bool, String name) {\n        this(name, bool, false);\n    }\n\n    protected ClassWithOverloadedConstructors(String name, boolean bool, boolean bool1) {\n        this.name = name;\n        this.bool = bool;\n        this.bool1 = bool1;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public boolean isBool() {\n        return bool;\n    }\n\n    public boolean isBool1() {\n        return bool1;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithOverloadedMethods.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithOverloadedMethods {\n\n    public String overloaded(double value, Parent parent) {\n        return \"parent\";\n    }\n\n    public String overloaded(double value, Child child) {\n        return \"child\";\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithOverriddenMethod.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithOverriddenMethod extends ClassWithStandardMethod {\n\n\t@Override\n\tpublic boolean myMethod(double value) {\n\t\treturn true;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrimitiveConstructors.java",
    "content": "package org.powermock.reflect.testclasses;\n\n/**\n *\n */\npublic class ClassWithPrimitiveConstructors {\n\n    private final long value;\n\n    public ClassWithPrimitiveConstructors(long value){\n\n        this.value = value;\n    }\n\n    public long getValue() {\n        return value;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrivateMethods.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\n@SuppressWarnings(\"unused\")\npublic class ClassWithPrivateMethods {\n\n\tprivate boolean primitiveMethod(double value) {\n\t\treturn true;\n\t}\n\n\tprivate boolean wrappedMethod(Double value) {\n\t\treturn true;\n\t}\n\n\tprivate String methodWithPrimitiveIntAndString(int myInt, String aString) {\n\t\treturn aString + Integer.toString(myInt);\n\t}\n\n\tprivate int methodWithPrimitiveAndWrappedInt(int myInt, Integer myInt2) {\n\t\treturn myInt + myInt2;\n\t}\n\n\tprivate String evilConcatOfStrings(String[] strings) {\n\t\tString returnValue = \"\";\n\t\tfor (String string : strings) {\n\t\t\treturnValue += string;\n\t\t}\n\t\treturn returnValue;\n\t}\n\n\tprivate int varArgsMethod(int... ints) {\n\t\tint sum = 0;\n\t\tfor (int i : ints) {\n\t\t\tsum += i;\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate ClassWithInternalState methodWithObjectArgument(ClassWithInternalState c) {\n\t\treturn c;\n\t}\n\n\tprivate Class<? super ClassWithInternalState> methodWithClassArgument(Class<? super ClassWithInternalState> c) {\n\t\treturn c;\n\t}\n\n\tprivate int varArgsMethod(int value) {\n\t\treturn value * 2;\n\t}\n\n\tprivate int varArgsMethod2(int value, int... moreValues) {\n\t\treturn value * 2 + moreValues.length;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSerializableState.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\nimport java.io.Serializable;\n\n@SuppressWarnings(\"unused\")\npublic class ClassWithSerializableState {\n\n\tprivate Serializable serializable;\n\n\tprivate Object[] objectArray;\n\n\tpublic void setSerializable(Serializable serializable) {\n\t\tthis.serializable = serializable;\n\t}\n\n\tpublic void setObjectArray(Object[] objectArray) {\n\t\tthis.objectArray = objectArray;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSeveralMethodsWithSameName.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithSeveralMethodsWithSameName {\n\n\tpublic double getDouble(double value) {\n\t\treturn value;\n\t}\n\n\tpublic double getDouble(double value1, double value2) {\n\t\treturn value1 + value2;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSeveralMethodsWithSameNameOneWithoutParameters.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithSeveralMethodsWithSameNameOneWithoutParameters {\n\n\tpublic double getDouble() {\n\t\treturn Double.MAX_VALUE;\n\t}\n\n\tpublic double getDouble(double value) {\n\t\treturn value;\n\t}\n\n\tpublic double getDouble(double value1, double value2) {\n\t\treturn value1 + value2;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSimpleInternalState.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithSimpleInternalState {\n\n\tprivate int someIntState = -1;\n\n\tprivate String someStringState = \"-1\";\n\n\tprivate static long someStaticLongState = -1L;\n\n\tpublic static long getLong() {\n\t\treturn someStaticLongState;\n\t}\n\n\tpublic long getSomeStaticLongState() {\n\t\treturn someStaticLongState;\n\t}\n\n\tpublic int getSomeIntState() {\n\t\treturn someIntState;\n\t}\n\n\tpublic String getSomeStringState() {\n\t\treturn someStringState;\n\t}\n\n\tpublic static void setLong(long state) {\n\t\tsomeStaticLongState = state;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSimpleStateOfSameType.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithSimpleStateOfSameType {\n\n    private String someStringState = \"-1\";\n    private String someOtherStringState = \"-1\";\n\n    public String getSomeStringState() {\n        return someStringState;\n    }\n\n    public String getSomeOtherStringState() {\n        return someOtherStringState;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithStandardMethod.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithStandardMethod {\n\n\tpublic boolean myMethod(double value) {\n\t\treturn true;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithStaticAndInstanceInternalStateOfSameType.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithStaticAndInstanceInternalStateOfSameType {\n\n    private String stringState = \"String state\";\n\n    private static String staticStringState = \"Static String state\";\n\n    public String getStaticStringState() {\n        return staticStringState;\n    }\n\n    public String getStringState() {\n        return stringState;\n    }\n\n    public static void reset() {\n      staticStringState = \"Static String state\";\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithStaticMethod.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithStaticMethod {\n\n    @SuppressWarnings({\"UnusedDeclaration\"})\n    private static String aStaticMethod(byte[] something) {\n        return \"hello\";\n    }\n\n    @SuppressWarnings({\"UnusedDeclaration\"})\n    private static String anotherStaticMethod(Object object, byte[] something) {\n        return object+\" \"+something;\n    }\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithUniquePrivateMethods.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\n@SuppressWarnings(\"unused\")\npublic class ClassWithUniquePrivateMethods {\n\n\tprivate boolean primitiveMethodWithOnlyOneArgument(double value) {\n\t\treturn true;\n\t}\n\n\tprivate static boolean primitiveStaticMethodWithOnlyOneArgument(double value) {\n\t\treturn true;\n\t}\n\n\tprivate boolean primitiveMethod(double value, double value2) {\n\t\treturn true;\n\t}\n\n\tprivate Object twoArgs(double value, double value2, Object obj) {\n\t\treturn new Object();\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithVarArgsConstructor.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithVarArgsConstructor {\n\t\n\t\n\tprivate final String[] strings;\n\n\tprivate ClassWithVarArgsConstructor(String...strings) {\n\t\tthis.strings = strings;\n\t}\n\n\tpublic String[] getStrings() {\n\t\treturn strings;\n\t}\n}\n\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithVarArgsConstructor2.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.powermock.reflect.testclasses;\n\npublic class ClassWithVarArgsConstructor2 {\n\n\tprivate final String[] strings;\n\n\tprivate ClassWithVarArgsConstructor2(String required, String... strings) {\n\t\tthis.strings = new String[strings.length + 1];\n\t\tthis.strings[0] = required;\n\t\tSystem.arraycopy(strings, 0, this.strings, 1, strings.length);\n\t}\n\n\tpublic String[] getStrings() {\n\t\treturn strings;\n\t}\n}\n"
  },
  {
    "path": "powermock-reflect/src/test/java/org/powermock/reflect/testclasses/Parent.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.powermock.reflect.testclasses;\n\npublic class Parent {\n\n}\n"
  },
  {
    "path": "powermock-release/build.gradle",
    "content": "apply from: \"${gradleScriptDir}/release/fullJars.gradle\"\napply from: \"${gradleScriptDir}/release/distZip.gradle\"\n\njar {\n    enabled = false\n}\n\nproject(\":powermock-release:powermock-easymock\") {\n\n    description = \"Single jar containing binaries for PowerMock core, EasyMock and all test framework modules.\"\n\n    def shadowDependencies = [\n            project(\":powermock-reflect\"),\n            project(\":powermock-core\"),\n            project(\":powermock-classloading:powermock-classloading-base\"),\n            project(\":powermock-api:powermock-api-support\"),\n            project(\":powermock-api:powermock-api-easymock\"),\n            project(\":powermock-modules:powermock-module-junit4-common\"),\n            project(\":powermock-modules:powermock-module-junit4\"),\n            project(\":powermock-modules:powermock-module-junit4-legacy\"),\n            project(\":powermock-modules:powermock-module-testng\"),\n            project(\":powermock-modules:powermock-module-testng-common\")\n    ]\n\n    dependencies {\n        runtime shadowDependencies\n    }\n\n    shadowJar {\n        shadowDependencies.each {\n            from(it.sourceSets.main.allSource) {\n                include \"**/*.java\"\n            }\n        }\n    }\n}\n\nproject(\":powermock-release:powermock-mockito2\") {\n\n    description = \"Single jar containing binaries for PowerMock core, Mockito 2.x and all test framework modules.\"\n\n    def shadowDependencies = [\n            project(\":powermock-reflect\"),\n            project(\":powermock-core\"),\n            project(\":powermock-classloading:powermock-classloading-base\"),\n            project(\":powermock-api:powermock-api-support\"),\n            project(\":powermock-api:powermock-api-mockito2\"),\n            project(\":powermock-modules:powermock-module-junit4-common\"),\n            project(\":powermock-modules:powermock-module-junit4\"),\n            project(\":powermock-modules:powermock-module-junit4-legacy\"),\n            project(\":powermock-modules:powermock-module-testng\"),\n            project(\":powermock-modules:powermock-module-testng-common\")\n    ]\n\n    dependencies {\n        runtime shadowDependencies\n    }\n\n    shadowJar {\n        shadowDependencies.each {\n            from(it.sourceSets.main.allSource) {\n                include \"**/*.java\"\n            }\n        }\n    }\n}\n\nproject(\":powermock-release:powermock-easymock-junit\") {\n\n    description = \"Single jar containing binaries for PowerMock core, JUnit and EasyMock modules.\"\n\n    dependencies {\n        compile(project(path:\":powermock-release:powermock-easymock\", configuration: \"shadow\"))\n        compile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        compile(\"org.easymock:easymock:${easymockVersion}\")\n        compile(\"org.objenesis:objenesis:${objenesisVersion}\")\n        compile(\"org.javassist:javassist:${javassistVersion}\")\n        compile(\"cglib:cglib-nodep:${cglibVersion}\")\n    }\n}\n\nproject(\":powermock-release:powermock-easymock-testng\") {\n\n    description = \"Single jar containing binaries for PowerMock core, TestNG and EasyMock modules.\"\n\n    dependencies {\n        compile(project(path:\":powermock-release:powermock-easymock\", configuration: \"shadow\"))\n        compile(\"org.testng:testng:${testngVersion}\")\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        compile(\"org.easymock:easymock:${easymockVersion}\")\n        compile(\"org.objenesis:objenesis:${objenesisVersion}\")\n        compile(\"org.javassist:javassist:${javassistVersion}\")\n        compile(\"cglib:cglib-nodep:${cglibVersion}\")\n    }\n}\n\nproject(\":powermock-release:powermock-mockito2-junit\") {\n\n    description = \"Single jar containing binaries for PowerMock core, JUnit and Mockito modules.\"\n\n    dependencies {\n        compile(project(path:\":powermock-release:powermock-mockito2\", configuration: \"shadow\"))\n        compile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        compile(\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n        compile(\"org.objenesis:objenesis:${objenesisVersion}\")\n        compile(\"org.javassist:javassist:${javassistVersion}\")\n        compile(\"cglib:cglib-nodep:${cglibVersion}\")\n    }\n}\n\nproject(\":powermock-release:powermock-mockito2-testng\") {\n\n    description = \"Single jar containing binaries for PowerMock core, TestNG and Mockito modules.\"\n\n    dependencies {\n        compile(project(path:\":powermock-release:powermock-mockito2\", configuration: \"shadow\"))\n        compile(\"org.testng:testng:${testngVersion}\")\n        compile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        compile(\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n        compile(\"org.objenesis:objenesis:${objenesisVersion}\")\n        compile(\"org.javassist:javassist:${javassistVersion}\")\n        compile(\"cglib:cglib-nodep:${cglibVersion}\")\n    }\n}"
  },
  {
    "path": "settings.gradle",
    "content": "include(\"powermock-reflect\")\ninclude(\"powermock-core\")\ninclude(\"powermock-api:powermock-api-support\")\ninclude(\"powermock-api:powermock-api-easymock\")\ninclude(\"powermock-api:powermock-api-mockito2\")\ninclude(\"powermock-classloading:powermock-classloading-base\")\ninclude(\"powermock-classloading:powermock-classloading-objenesis\")\ninclude(\"powermock-classloading:powermock-classloading-xstream\")\ninclude(\"powermock-modules:powermock-module-javaagent\")\ninclude(\"powermock-modules:powermock-module-junit4-common\")\ninclude(\"powermock-modules:powermock-module-junit4\")\ninclude(\"powermock-modules:powermock-module-junit4-legacy\")\ninclude(\"powermock-modules:powermock-module-junit4-rule\")\ninclude(\"powermock-modules:powermock-module-junit4-rule-agent\")\ninclude(\"powermock-modules:powermock-module-testng-common\")\ninclude(\"powermock-modules:powermock-module-testng\")\ninclude(\"powermock-modules:powermock-module-testng-agent\")\ninclude(\"tests:utils\")\ninclude(\"tests:junit4\")\ninclude(\"tests:testng\")\ninclude(\"tests:easymock:junit4-agent\")\ninclude(\"tests:easymock:junit4-legacy\")\ninclude(\"tests:easymock:junit4\")\ninclude(\"tests:easymock:junit45\")\ninclude(\"tests:easymock:junit47\")\ninclude(\"tests:easymock:junit48\")\ninclude(\"tests:easymock:junit410\")\ninclude(\"tests:easymock:junit412\")\ninclude(\"tests:easymock:testng\")\ninclude(\"tests:easymock:testng-agent\")\ninclude(\"tests:mockito:junit4\")\ninclude(\"tests:mockito:inline\")\ninclude(\"tests:mockito:junit49\")\ninclude(\"tests:mockito:junit4-agent\")\ninclude(\"tests:mockito:junit4-delegate\")\ninclude(\"tests:mockito:junit4-rule-objenesis\")\ninclude(\"tests:mockito:junit4-rule-xstream\")\ninclude(\"tests:mockito:testng\")\ninclude(\"tests:java8:mockito-junit4\")\ninclude(\"tests:java8:mockito-junit4-agent\")\ninclude(\"tests:java8:mockito-junit4-rule-xstream\")\ninclude(\"tests:java8:easymock-junit4\")\ninclude(\"tests:java11:mockito-junit4\")\ninclude(\"powermock-release:powermock-easymock\")\ninclude(\"powermock-release:powermock-mockito2\")\ninclude(\"powermock-release:powermock-easymock-junit\")\ninclude(\"powermock-release:powermock-easymock-testng\")\ninclude(\"powermock-release:powermock-mockito2-junit\")\ninclude(\"powermock-release:powermock-mockito2-testng\")\n"
  },
  {
    "path": "tests/build.gradle",
    "content": "def subprojects = project(\":tests\").subprojects  - project(\":tests:easymock\")\n\next {\n    bintrayAutoPublish = false\n    mavenCentralSync = false\n}\n\njar{\n    enabled = false\n}\n\nconfigure(subprojects) { project ->\n    ext {\n        bintrayAutoPublish = false\n        mavenCentralSync = false\n    }\n\n    apply from: \"${gradleScriptDir}/java-module.gradle\"\n\n    test {\n        jvmArgs \"-XX:MaxPermSize=256m\"\n    }\n}\n\nproject(\":tests:utils\"){\n    description = \"Common set of classes to test PowerMock features in mocking framework modules.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        compile(\"javax.servlet:servlet-api:${servletVersion}\")\n    }\n}\n\nproject(\":tests:junit4\"){\n    description = \"Tests for junit4.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(project(\":powermock-modules:powermock-module-junit4\"))\n        testCompile(\"junit:junit:${junitVersion}\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.easymock:easymock:${easymockVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n        testCompile(\"com.github.stefanbirkner:system-rules:${systemRulesVersion}\")\n    }\n}\n\nproject(\":tests:testng\") {\n    description = \"Tests for testng module.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(project(\":powermock-modules:powermock-module-testng\"))\n        testCompile(\"org.testng:testng:${testngVersion}\")\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n\n    test {\n        useTestNG() {\n            suites 'suite.xml'\n        }\n    }\n}"
  },
  {
    "path": "tests/easymock/build.gradle",
    "content": "List easymock = [\n        \"org.easymock:easymock:${easymockVersion}\",\n        \"org.assertj:assertj-core:${assertjVersion}\",\n        \"org.hamcrest:hamcrest-core:${hamcrestVersion}\",\n        project(\":powermock-api:powermock-api-easymock\"),\n        project(\":tests:utils\")\n]\n\nproject(\":tests:easymock:junit4-agent\") {\n    description = \"Tests for PowerMock Java agent with JUnit4 and Easymock\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:${junitVersion}\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-javaagent\"))\n        testCompile(project(\":powermock-modules:powermock-module-junit4-rule-agent\"))\n    }\n\n    def pathToAgent = project(\":powermock-modules:powermock-module-javaagent\").jar.outputs.files.getFiles().getAt(0)\n\n    test {\n        jvmArgs \"-javaagent:${pathToAgent}\"\n    }\n}\n\nproject(\":tests:easymock:junit4-legacy\"){\n    description = \"Tests for EasyMock module with JUnit 4.0-4.3.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:4.3\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-junit4-legacy\"))\n    }\n}\n\nproject(\":tests:easymock:junit4\"){\n    description = \" Tests for EasyMock module with JUnit 4.x\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:4.4\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-junit4\")){\n            exclude group: 'junit', module: 'junit'\n        }\n    }\n\n    test{\n        exclude \"**/*Defect*\"\n    }\n}\n\nproject(\":tests:easymock:junit45\"){\n    description = \" Tests for EasyMock module with JUnit 4.5.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:4.5\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-junit4\")){\n            exclude group: 'junit', module: 'junit'\n        }\n        testCompile files(project(\":tests:easymock:junit4\").sourceSets.test.output)\n    }\n\n    test{\n        exclude \"**/*Defect*\"\n    }\n}\n\nproject(\":tests:easymock:junit47\"){\n    description = \" Tests for EasyMock module with JUnit 4.7.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:4.7\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-junit4\")){\n            exclude group: 'junit', module: 'junit'\n        }\n        testCompile files(project(\":tests:easymock:junit4\").sourceSets.test.output)\n    }\n}\n\nproject(\":tests:easymock:junit48\"){\n    description = \" Tests for EasyMock module with JUnit 4.8.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:4.8.2\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-junit4\")){\n            exclude group: 'junit', module: 'junit'\n        }\n        testCompile files(project(\":tests:easymock:junit4\").sourceSets.test.output)\n    }\n}\n\nproject(\":tests:easymock:junit410\"){\n    description = \" Tests for EasyMock module with JUnit 4.10.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:4.10\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-junit4\")){\n            exclude group: 'junit', module: 'junit'\n        }\n        testCompile files(project(\":tests:easymock:junit4\").sourceSets.test.output)\n    }\n}\n\nproject(\":tests:easymock:junit412\"){\n    description = \" Tests for EasyMock module with JUnit 4.12.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        testCompile(\"junit:junit:4.12\")\n        testCompile easymock\n        testCompile(project(\":powermock-modules:powermock-module-junit4\")){\n            exclude group: 'junit', module: 'junit'\n        }\n        testCompile files(project(\":tests:easymock:junit4\").sourceSets.test.output)\n    }\n}\n\nproject(\":tests:easymock:testng\"){\n    description = \"Tests for EasyMock module with TestNG.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        compile(project(\":powermock-modules:powermock-module-testng\"))\n        testCompile easymock\n        testCompile(\"org.testng:testng:${testngVersion}\")\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n    }\n\n    test{\n        useTestNG(){\n            suites 'suite.xml'\n        }\n    }\n}\n\nproject(\":tests:easymock:testng-agent\"){\n    description = \"Tests for EasyMock module with TestNG.\"\n\n    dependencies {\n        compile(project(\":powermock-core\"))\n        compile(project(\":powermock-modules:powermock-module-testng\"))\n        testCompile easymock\n        testCompile(\"org.testng:testng:${testngVersion}\")\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n        testCompile(project(\":powermock-modules:powermock-module-testng-agent\"))\n    }\n\n    def pathToAgent = project(\":powermock-modules:powermock-module-javaagent\").jar.outputs.files.getFiles().getAt(0)\n\n    test {\n        useTestNG(){\n            suites 'suite.xml'\n        }\n\n        jvmArgs \"-javaagent:${pathToAgent}\"\n    }\n}"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsageTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.interfacemethodfinding;\n\nimport org.easymock.EasyMock;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.PowerMock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\n\n/**\n * There was a bug in PowerMock 1.2 and its predecessors that made PowerMock\n * {@link WhiteboxImpl#getMethod(Class, Class...)} fail when invoking proxified\n * interface methods declared in extended interfaces. E.g. if interface A\n * extends B & C and a method was declared in B it wouldn't be found by\n * {@link WhiteboxImpl#getMethod(Class, Class...)} since it only used to\n * traverse the class hierarchy and not the structure of the extended\n * interfaces. This was fixed in version 1.3 and this test demonstrates that\n * it's solved.\n * <p>\n * Thanks to Lokesh Vaddi for finding this bug and to provide an example.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { InterfaceMethodHierarchyUsage.class, WsUtil.class })\npublic class InterfaceMethodHierarchyUsageTest {\n\n\tprivate InterfaceMethodHierarchyUsage myClass;\n\n\t@Test\n\tpublic void assertMethodsAreFoundInInterfaceHierarchy() throws Exception {\n\t\tConnection mockConnection = PowerMock.createMock(Connection.class);\n\t\tPowerMock.mockStaticPartial(WsUtil.class, \"getConnection\");\n\t\tPreparedStatement mockPrepared = PowerMock.createMock(PreparedStatement.class);\n\t\tEasyMock.expect(WsUtil.getConnection()).andReturn(mockConnection);\n\t\tEasyMock.expect(mockConnection.prepareStatement(\"select * from emp\")).andReturn(mockPrepared);\n\t\tmockConnection.close();\n\t\tEasyMock.expectLastCall();\n\t\tmockPrepared.close();\n\t\tEasyMock.expectLastCall();\n\n\t\tPowerMock.replayAll();\n\t\tmyClass = new InterfaceMethodHierarchyUsage();\n\t\tmyClass.usePreparedStatement();\n\t\tPowerMock.verifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/abstractmocking/AbstractMethodMockingTest.java",
    "content": "package samples.junit4.abstractmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.abstractmocking.AbstractMethodMocking;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(AbstractMethodMocking.class)\npublic class AbstractMethodMockingTest {\n\n\t@Test\n\tpublic void testMockingOfAbstractMethod() throws Exception {\n\t\tfinal String value = \"a string\";\n\t\tAbstractMethodMocking tested = createPartialMock(\n\t\t\t\tAbstractMethodMocking.class, \"getIt\");\n\n\t\texpectPrivate(tested, \"getIt\").andReturn(value);\n\n\t\treplay(tested);\n\n\t\tassertEquals(value, tested.getValue());\n\n\t\tverify(tested);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/AnnotationDemoWithSetupMethodTest.java",
    "content": "package samples.junit4.annotationbased;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n/**\n * Verifies that PowerMock test listeners works correctly with setup methods.\n */\n@RunWith(PowerMockRunner.class)\npublic class AnnotationDemoWithSetupMethodTest {\n\n\t@org.powermock.api.easymock.annotation.Mock\n\tprivate Service serviceMock;\n\n\tprivate AnnotationDemo tested;\n\n\t@Before\n\tpublic void setup() {\n\t\ttested = new AnnotationDemo(serviceMock);\n\t}\n\n\t@Test\n\tpublic void assertInjectionWorked() throws Exception {\n\t\tfinal String expected = \"mock\";\n\t\texpect(serviceMock.getServiceMessage()).andReturn(expected);\n\n\t\treplayAll();\n\n\t\tassertEquals(expected, tested.getServiceMessage());\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.testlisteners.FieldDefaulter;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with multiple test\n * listeners.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\n@PowerMockListener( { FieldDefaulter.class })\npublic class FinalDemoWithAnnotationInjectionAndFieldDefaulterTest {\n\n    @SuppressWarnings(\"unused\")\n    // Asserts that the FieldDefaulter handles primitive types.\n    private int intType = 6;\n\n    @Mock\n    private FinalDemo tested;\n\n    @Test\n    public void testSay() throws Exception {\n        String expected = \"Hello altered World\";\n        expect(tested.say(\"hello\")).andReturn(\"Hello altered World\");\n        replay(tested);\n\n        String actual = tested.say(\"hello\");\n\n        verify(tested);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n\n        // Should still be mocked by now.\n        try {\n            tested.say(\"world\");\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected method call FinalDemo.say(\\\"world\\\"):\", e.getMessage());\n        }\n\n    }\n\n    @Test\n    public void testSayFinalNative() throws Exception {\n        String expected = \"Hello altered World\";\n        expect(tested.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n        replay(tested);\n\n        String actual = tested.sayFinalNative(\"hello\");\n\n        verify(tested);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n\n        // Should still be mocked by now.\n        try {\n            tested.sayFinalNative(\"world\");\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected method call FinalDemo.sayFinalNative(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with one listeners.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class FinalDemoWithAnnotationInjectionTest {\n\n\t@Mock\n\tprivate FinalDemo tested;\n\n\t@Test\n\tpublic void testSay() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.say(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testSayFinalNative() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.sayFinalNative(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should no longer be mocked by now.\n\t\ttry {\n\t\t\ttested.sayFinalNative(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.sayFinalNative(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithNiceAnnotationInjectionTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.MockNice;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with one listeners\n * injecting mocks to fields annotated with {@link MockNice}.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class FinalDemoWithNiceAnnotationInjectionTest {\n\n\t@MockNice\n\tprivate FinalDemo tested;\n\n\t@Test\n\tpublic void testSay() throws Exception {\n\t\tString expected = null;\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\tString actual2 = tested.say(\"world\");\n\t\tassertEquals(expected, actual2);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithStrictAnnotationInjectionTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.MockNice;\nimport org.powermock.api.easymock.annotation.MockStrict;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with one listeners\n * injecting mocks to fields annotated with {@link MockNice}.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class FinalDemoWithStrictAnnotationInjectionTest {\n\n\t@MockStrict\n\tprivate FinalDemo tested;\n\n\t@Test\n\tpublic void testMockStrictOk() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\n\t\texpect(tested.say(\"hello\")).andReturn(expected);\n\t\texpect(tested.say(\"hello2\")).andReturn(expected);\n\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"hello\");\n\t\tString actual2 = tested.say(\"hello2\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual2);\n\t}\n\n\t@Test(expected = AssertionError.class)\n\tpublic void testMockStrictNotOk() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\n\t\texpect(tested.say(\"hello\")).andReturn(expected);\n\n\t\treplay(tested);\n\n\t\ttested.say(\"hello2\");\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectEasymockAnnotationTest.java",
    "content": "package samples.junit4.annotationbased;\n\nimport org.easymock.Mock;\nimport org.easymock.TestSubject;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.injectmocks.InjectDemo;\nimport samples.injectmocks.InjectDependencyHolder;\nimport samples.injectmocks.InjectDependencyHolderQualifier;\n\nimport static org.junit.Assert.assertNotNull;\n\n/**\n * Asserts that {@link @TestSubject} with PowerMock and mock witch created via @org.easymock.Mock.\n */\n@RunWith(PowerMockRunner.class)\npublic class TestSubjectEasymockAnnotationTest {\n\n    @SuppressWarnings(\"unused\")\n    @Mock\n    private InjectDemo injectDemoEasymock;\n\n    @TestSubject\n    private final InjectDependencyHolder dependencyHolder = new InjectDependencyHolder();\n\n    @SuppressWarnings(\"unused\")\n    @Mock(fieldName = \"injectDemoQualifier\")\n    private InjectDemo injectDemoQualifierEasymock;\n\n    @TestSubject\n    private final InjectDependencyHolderQualifier dependencyHolderQualifier = new InjectDependencyHolderQualifier();\n\n    @Test\n    public void injectMocksWorksWithEasymock() {\n        assertNotNull(\"dependencyHolder is null\", dependencyHolder.getInjectDemo());\n    }\n\n    @Test\n    public void injectMocksWorksWithEasymockQualifier() {\n        assertNotNull(\"dependencyHolder is null\", dependencyHolderQualifier.getInjectDemoQualifier());\n    }\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectPowermockAnnotationTest.java",
    "content": "package samples.junit4.annotationbased;\n\nimport org.easymock.TestSubject;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.injectmocks.InjectDemo;\nimport samples.injectmocks.InjectDependencyHolder;\nimport samples.injectmocks.InjectDependencyHolderQualifier;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.powermock.api.easymock.PowerMock.expectPrivate;\nimport static org.powermock.api.easymock.PowerMock.replay;\n\n/**\n * Asserts that {@link @TestSubject} with PowerMock and mock witch created via @org.powermock.api.easymock.annotation.Mock.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(InjectDemo.class)\npublic class TestSubjectPowermockAnnotationTest {\n\n    @SuppressWarnings(\"unused\")\n    @Mock\n    private InjectDemo injectDemoEasymock;\n\n    @TestSubject\n    private final InjectDependencyHolder dependencyHolder = new InjectDependencyHolder();\n\n    @SuppressWarnings(\"unused\")\n    @Mock(fieldName = \"injectDemoQualifier\")\n    private InjectDemo injectDemoQualifierEasymock;\n\n    @TestSubject\n    private final InjectDependencyHolderQualifier dependencyHolderQualifier = new InjectDependencyHolderQualifier();\n\n\n    @Test\n    public void should_inject_mock_without_quantifier() throws Exception {\n\n        final InjectDemo tested = dependencyHolder.getInjectDemo();\n        assertNotNull(\"dependencyHolder is null\", tested);\n\n        String expected = \"Hello altered World\";\n        expectPrivate(tested,\"say\",\"hello\").andReturn(\"Hello altered World\");\n        replay(tested);\n\n        String actual = Whitebox.invokeMethod(tested,\"say\", \"hello\");\n\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void should_inject_mock_with_quantifier() throws Exception {\n\n        InjectDemo tested = dependencyHolderQualifier.getInjectDemoQualifier();\n        assertNotNull(\"dependencyHolderQualifier is null\", tested);\n\n        String expected = \"Hello altered World\";\n        expectPrivate(tested,\"say\",\"hello\").andReturn(\"Hello altered World\");\n        replay(tested);\n\n        String actual = Whitebox.invokeMethod(tested,\"say\", \"hello\");\n\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n\n    }\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/assume/AssumeTest.java",
    "content": "package samples.junit4.assume;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assume.assumeTrue;\n\n@RunWith(PowerMockRunner.class)\npublic class AssumeTest {\n\n    @Test\n    public void assumesWorkWithPowerMockForJUnit44() throws Exception {\n        // When\n        assumeTrue(false);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/classhierarchy/CommonParentTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.classhierarchy;\n\nimport org.easymock.EasyMock;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.PowerMock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.classhierarchy.ChildA;\nimport samples.classhierarchy.ChildB;\nimport samples.classhierarchy.Parent;\n\nimport static org.junit.Assert.assertEquals;\n\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({ChildA.class, ChildB.class, Parent.class})\npublic class CommonParentTest {\n\n\t@Test\n\tpublic void testPossibleToMockTwoClassesWithSameParent() throws Exception {\n\t\tChildA a = PowerMock.createMock(ChildA.class);\n\t\tEasyMock.expect(a.getValue()).andReturn(5);\n\t\t\n\t\tPowerMock.replay(a);\n\t\t\n\t\tassertEquals(5, a.getValue());\n\t\t\n\t\tPowerMock.verify(a);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/classwithinnermembers/ClassWithInnerMembersTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.classwithinnermembers;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.classwithinnermembers.ClassWithInnerMembers;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test PowerMock's basic support for inner (member) and local classes.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ClassWithInnerMembers.class)\npublic class ClassWithInnerMembersTest {\n\n\t@Test\n\tpublic void assertStaticMemberClassMockingWorksWithNoConstructorArguments() throws Exception {\n\t\tClass<Object> innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, \"MyInnerClass\");\n\t\tObject innerClassMock = createMock(innerClassType);\n\t\texpectNew(innerClassType).andReturn(innerClassMock);\n\t\texpectPrivate(innerClassMock, \"doStuff\").andReturn(\"something else\");\n\n\t\treplayAll();\n\n\t\tassertEquals(\"something else\", new ClassWithInnerMembers().getValue());\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertStaticMemberClassMockingWorksWithConstructorArguments() throws Exception {\n\t\tClass<Object> innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, \"StaticInnerClassWithConstructorArgument\");\n\t\tObject innerClassMock = createMock(innerClassType);\n\t\texpectNew(innerClassType, \"value\").andReturn(innerClassMock);\n\t\texpectPrivate(innerClassMock, \"doStuff\").andReturn(\"something else\");\n\n\t\treplayAll();\n\n\t\tassertEquals(\"something else\", new ClassWithInnerMembers().getValueForStaticInnerClassWithConstructorArgument());\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertLocalClassMockingWorks() throws Exception {\n\n\t\tfinal Class<Object> type = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 1, \"MyLocalClass\");\n\t\tObject innerClassMock = createMock(type);\n\t\texpectNew(type).andReturn(innerClassMock);\n\t\texpectPrivate(innerClassMock, \"doStuff\").andReturn(\"something else\");\n\n\t\treplayAll();\n\n\t\tassertEquals(\"something else\", new ClassWithInnerMembers().getLocalClassValue());\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertLocalClassMockingWorksWithArguments() throws Exception {\n\t\tfinal Class<Object> type = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 2, \"MyLocalClass\");\n\t\tObject innerClassMock = createMock(type);\n\t\texpectNew(type, \"my value\").andReturn(innerClassMock);\n\t\texpectPrivate(innerClassMock, \"doStuff\").andReturn(\"something else\");\n\n\t\treplayAll();\n\n\t\tassertEquals(\"something else\", new ClassWithInnerMembers().getLocalClassValueWithArgument());\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertNonStaticMemberClassMockingWorksWithArguments() throws Exception {\n\t\tClass<Object> innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, \"MyInnerClassWithConstructorArgument\");\n\t\tObject innerClassMock = createMock(innerClassType);\n\t\texpectNew(innerClassType, \"value\").andReturn(innerClassMock);\n\t\texpectPrivate(innerClassMock, \"doStuff\").andReturn(\"something else\");\n\n\t\treplayAll();\n\n\t\tassertEquals(\"something else\", new ClassWithInnerMembers().getValueForInnerClassWithConstructorArgument());\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertThatAnonymousInnerClassesWorks() throws Exception {\n\t\tfinal Class<Object> type = Whitebox.getAnonymousInnerClassType(ClassWithInnerMembers.class, 1);\n\t\tObject innerClassMock = createMock(type);\n\t\texpectNew(type).andReturn(innerClassMock);\n\t\texpectPrivate(innerClassMock, \"doStuff\").andReturn(\"something else\");\n\n\t\treplayAll();\n\n\t\tassertEquals(\"something else\", new ClassWithInnerMembers().getValueForAnonymousInnerClass());\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/console/ConsoleTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.console;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.io.Console;\n\nimport static org.powermock.api.easymock.PowerMock.createMock;\n\n/**\n * Asserts that PowerMock can mock the Console class. This failed in version 1.4\n * when the DefaultFieldValueGenerator was introduced. This tests makes sure\n * that the DefaultFieldValueGenerator can generate default values for field\n * that are interfaces and abstract with no inheritable constructor.\n */\n@RunWith(PowerMockRunner.class)\npublic class ConsoleTest {\n\n\t@Test\n\tpublic void canMockConsole() throws Exception {\n\t\tcreateMock(Console.class);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/constructor/PrivateConstructorInstantiationDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.constructor;\n\nimport org.junit.Test;\nimport samples.constructor.PrivateConstructorInstantiationDemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.reflect.Whitebox.invokeConstructor;\n\n\npublic class PrivateConstructorInstantiationDemoTest {\n\n\t@Test\n\tpublic void testGetState_noArgConstructor() throws Exception {\n\t\tfinal int expected = 42;\n\t\tPrivateConstructorInstantiationDemo tested = invokeConstructor(PrivateConstructorInstantiationDemo.class);\n\t\tint actual = tested.getState();\n\n\t\tassertEquals(\"Expected and actual did not match.\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testGetState_intConstructor() throws Exception {\n\t\tfinal int expected = 12;\n\t\tPrivateConstructorInstantiationDemo tested = invokeConstructor(\n\t\t\t\tPrivateConstructorInstantiationDemo.class, expected);\n\t\tint actual = tested.getState();\n\n\t\tassertEquals(\"Expected and actual did not match.\", expected, actual);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/constructor/PublicConstructorWithDependencyDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.constructor;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport samples.Service;\nimport samples.constructor.PublicConstructorWithDependencyDemo;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.junit.Assert.*;\nimport static org.powermock.api.easymock.PowerMock.createPartialMock;\n\n/**\n * Verifies that error messages are correct when the constructor cannot be found\n * with partial mocking. This test asserts that the\n * http://code.google.com/p/powertest/issues/detail?id=59 has been fixed.\n * \n */\npublic class PublicConstructorWithDependencyDemoTest {\n\n    private Service serviceMock;\n\n    @Before\n    public void setUp() {\n        serviceMock = createMock(Service.class);\n    }\n\n    @After\n    public void tearDown() {\n        serviceMock = null;\n    }\n\n    /**\n     * \n     * @throws Exception\n     */\n    @Test\n    public void testConstructorFound() throws Exception {\n        PublicConstructorWithDependencyDemo tested = createPartialMock(PublicConstructorWithDependencyDemo.class,\n                new String[] { \"aMethod\" }, serviceMock);\n\n        assertSame(serviceMock, tested.getService());\n    }\n\n    /**\n     * \n     * @throws Exception\n     */\n    @Test\n    public void testConstructorNotFound() throws Exception {\n        try {\n            createPartialMock(PublicConstructorWithDependencyDemo.class, new String[] { \"aMethod\" }, serviceMock, \"bad argument\");\n            fail(\"Should throw ConstructorNotFoundException.\");\n        } catch (ConstructorNotFoundException e) {\n            assertEquals(\"No constructor found in class '\" + PublicConstructorWithDependencyDemo.class.getName()\n                    + \"' with parameter types: [ \" + Service.class.getName() + \", \" + String.class.getName() + \" ].\", e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/constructorargs/ConstructorArgsDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.constructorargs;\n\nimport org.easymock.ConstructorArgs;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.constructorargs.ConstructorArgsDemo;\n\nimport java.lang.reflect.Constructor;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * This test demonstrates the ability to invoke a specific constructor after\n * creating the mock object.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ConstructorArgsDemo.class)\npublic class ConstructorArgsDemoTest {\n\n\t@Test\n\tpublic void testGetTheSecret_noConstructor() throws Exception {\n\t\tConstructorArgsDemo tested = createMock(ConstructorArgsDemo.class);\n\t\tassertNull(Whitebox.getInternalState(tested, \"secret\", ConstructorArgsDemo.class));\n\t}\n\n\t@Test\n\tpublic void testGetTheSecret_defaultConstructor() throws Exception {\n\t\tfinal Constructor<ConstructorArgsDemo> constructor = ConstructorArgsDemo.class.getConstructor((Class<?>[]) null);\n\t\tConstructorArgsDemo tested = createMock(ConstructorArgsDemo.class, new ConstructorArgs(constructor));\n\t\tassertEquals(\"default\", Whitebox.getInternalState(tested, \"secret\", ConstructorArgsDemo.class));\n\t}\n\n\t@Test\n\tpublic void testGetTheSecret_stringConstructor() throws Exception {\n\t\tfinal String expected = \"my own secret\";\n\t\tConstructorArgsDemo tested = createMock(ConstructorArgsDemo.class, expected);\n\t\tassertEquals(expected, Whitebox.getInternalState(tested, \"secret\", ConstructorArgsDemo.class));\n\t}\n\n\t@Test\n\tpublic void testGetTheSecret_stringConstructorAndMockedPrivateSecret() throws Exception {\n\t\tfinal String originalSecret = \"my own secret\";\n\t\tConstructorArgsDemo tested = createPartialMock(ConstructorArgsDemo.class, new String[] { \"theSecretIsPrivate\" }, originalSecret);\n\t\tassertEquals(originalSecret, Whitebox.getInternalState(tested, \"secret\", ConstructorArgsDemo.class));\n\n\t\tfinal String myNewSecret = \"my new secret\";\n\t\texpectPrivate(tested, \"theSecretIsPrivate\").andReturn(myNewSecret);\n\n\t\treplay(tested);\n\n\t\tfinal String actual = tested.getTheSecret();\n\n\t\tverify(tested);\n\n\t\tassertEquals(myNewSecret, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/easymock/EasyMockAndPowerMockMixTest.java",
    "content": "package samples.junit4.easymock;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.Service;\nimport samples.privatefield.SimplePrivateFieldServiceClass;\n\nimport static org.easymock.EasyMock.*;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.reflect.Whitebox.setInternalState;\n\n/**\n * This test verifies that you can mix EasyMock and PowerMock.\n */\n@RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor(\"samples.privatefield.SimplePrivateFieldServiceClass\")\npublic class EasyMockAndPowerMockMixTest {\n\n\t@Test\n\tpublic void testSimplePrivateFieldServiceClass() throws Exception {\n\t\tSimplePrivateFieldServiceClass tested = new SimplePrivateFieldServiceClass();\n\t\tService serviceMock = createMock(Service.class);\n\t\tsetInternalState(tested, \"service\", serviceMock, SimplePrivateFieldServiceClass.class);\n\n\t\tfinal String expected = \"Hello world!\";\n\t\texpect(serviceMock.getServiceMessage()).andReturn(expected);\n\n\t\treplay(serviceMock);\n\t\tfinal String actual = tested.useService();\n\n\t\tverify(serviceMock);\n\n\t\tassertEquals(expected, actual);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/enummocking/EnumMockingTest.java",
    "content": "package samples.junit4.enummocking;\n\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.enummocking.MyEnum;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(MyEnum.class)\npublic class EnumMockingTest {\n\n\t@Test\n\tpublic void assertMockingOfStaticMethodInEnumWorks() throws Exception {\n\t\tfinal String expected = \"something else\";\n\t\tmockStatic(MyEnum.class);\n\n\t\texpect(MyEnum.getString()).andReturn(expected);\n\n\t\treplayAll();\n\n\t\tfinal String actual = MyEnum.getString();\n\n\t\tverifyAll();\n\n\t\tAssert.assertEquals(expected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/equalswithgetclass/EqualsWithGetClassTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.equalswithgetclass;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.equalswithgetclass.EqualsWithGetClass;\n\nimport static org.junit.Assert.assertTrue;\nimport static org.powermock.api.easymock.PowerMock.createMock;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\n\n/**\n * Demonstrates that PowerMock ignores the call to getClass by default.\n * Demonstrates that <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=190\">issue 190</a>\n * is resolved.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(EqualsWithGetClass.class)\npublic class EqualsWithGetClassTest {\n\n    @Test\n    public void callingGetClassOnAMockWorksWhenTheCallWasUnexpected() throws Exception {\n        EqualsWithGetClass mock1 = createMock(EqualsWithGetClass.class);\n        replayAll();\n        assertTrue(mock1.getClass().getName().startsWith(EqualsWithGetClass.class.getName()));\n    }\n\n    @Test(expected = AssertionError.class)\n    public void callingGetClassOnAMockFailsWhenTheCallWasUnexpectedAndMockStandardMethodsIsSet() throws Exception {\n        try {\n            EqualsWithGetClass mock1 = createMock(EqualsWithGetClass.class);\n            MockGateway.MOCK_GET_CLASS_METHOD = true;\n            replayAll();\n            mock1.getClass();\n        } finally {\n            MockGateway.MOCK_GET_CLASS_METHOD = false;\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewCases.java",
    "content": "package samples.junit4.expectnew;\n\nimport org.junit.Test;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport samples.Service;\nimport samples.expectnew.CreationException;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.expectnew.ExpectNewServiceUser;\nimport samples.expectnew.ITarget;\nimport samples.expectnew.Target;\nimport samples.expectnew.VarArgsConstructorDemo;\nimport samples.newmocking.MyClass;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.easymock.EasyMock.aryEq;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertSame;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.createMock;\nimport static org.powermock.api.easymock.PowerMock.expectNew;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\npublic abstract class ExpectNewCases {\n\n    public static final String TARGET_NAME = \"MyTarget\";\n    public static final int TARGET_ID = 1;\n    public static final String UNKNOWN_TARGET_NAME = \"Unknown2\";\n    public static final int UNKNOWN_TARGET_ID = -11;\n\n    @Test\n    public void testNewWithCheckedException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing checked exception\";\n        expectNew(MyClass.class).andThrow(new IOException(expectedFailMessage));\n\n        replay(MyClass.class);\n\n        try {\n            tested.throwExceptionAndWrapInRunTimeWhenInvoction();\n            fail(\"Should throw a checked Exception!\");\n        } catch (RuntimeException e) {\n            assertTrue(e.getCause() instanceof IOException);\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verify(MyClass.class);\n    }\n\n    @Test\n    public void testGetMessage() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        expect(myClassMock.getMessage()).andReturn(\"Hello altered World\");\n\n        replay(myClassMock, MyClass.class);\n\n        String actual = tested.getMessage();\n\n        verify(myClassMock, MyClass.class);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testGetMessageWithArgument() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = createMock(MyClass.class);\n        expectNew(MyClass.class).andReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        expect(myClassMock.getMessage(\"test\")).andReturn(\"Hello altered World\");\n        replay(myClassMock, MyClass.class);\n\n        String actual = tested.getMessageWithArgument();\n\n        verify(myClassMock, MyClass.class);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testInvokeVoidMethod() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = createMock(MyClass.class);\n        expectNew(MyClass.class).andReturn(myClassMock);\n\n        myClassMock.voidMethod();\n        expectLastCall().times(1);\n\n        replay(myClassMock, MyClass.class);\n\n        tested.invokeVoidMethod();\n\n        verify(myClassMock, MyClass.class);\n    }\n\n    @Test\n    public void testNewWithRuntimeException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing\";\n        expectNew(MyClass.class).andThrow(new RuntimeException(expectedFailMessage));\n\n        replay(MyClass.class);\n\n        try {\n            tested.throwExceptionWhenInvoction();\n            fail(\"Should throw RuntimeException!\");\n        } catch (RuntimeException e) {\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verify(MyClass.class);\n    }\n\n    @Test\n    public void testPreviousProblemsWithByteCodeManipulation() throws Exception {\n        MyClass myClassMock1 = createMock(MyClass.class);\n        expect(myClassMock1.getMessage()).andReturn(\"Hello\");\n        expect(myClassMock1.getMessage()).andReturn(\"World\");\n        replay(myClassMock1);\n        assertEquals(\"Hello\", myClassMock1.getMessage());\n        assertEquals(\"World\", myClassMock1.getMessage());\n        verify(myClassMock1);\n    }\n\n    @Test\n    public void testMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n        MyClass myClassMock2 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1);\n        expectNew(MyClass.class).andReturn(myClassMock2);\n\n        expect(myClassMock1.getMessage()).andReturn(\"Hello \");\n        expect(myClassMock2.getMessage()).andReturn(\"World\");\n\n        replay(myClassMock1, myClassMock2, MyClass.class);\n\n        final String actual = tested.multipleNew();\n\n        verify(myClassMock1, myClassMock2, MyClass.class);\n\n        assertEquals(\"Hello World\", actual);\n    }\n\n    @Test\n    public void testSimpleMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(3);\n\n        replay(myClassMock1, MyClass.class);\n\n        tested.simpleMultipleNew();\n\n        verify(myClassMock1, MyClass.class);\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(4);\n\n        replay(myClassMock1, MyClass.class);\n\n        tested.simpleMultipleNew();\n\n        try {\n            verify(myClassMock1, MyClass.class);\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Expectation failure on verify:\" + \"\\n    samples.newmocking.MyClass(): expected: 4, actual: 3\", e\n                    .getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(2);\n\n        replay(myClassMock1, MyClass.class);\n        try {\n            tested.simpleMultipleNew();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected constructor call samples.newmocking.MyClass():\"\n                    + \"\\n    samples.newmocking.MyClass(): expected: 2, actual: 3\", e.getMessage());\n        }\n    }\n\n    /**\n     * Verifies that the issue\n     * http://code.google.com/p/powermock/issues/detail?id=10 is solved.\n     */\n    @Test\n    public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(2);\n\n        replay(myClassMock1, MyClass.class);\n        try {\n            Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected constructor call samples.newmocking.MyClass():\"\n                    + \"\\n    samples.newmocking.MyClass(): expected: 2, actual: 3\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_ok() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(3);\n\n        replay(myClassMock1, MyClass.class);\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n    }\n\n    @Test\n    public void testSimpleSingleNew_withOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).once();\n\n        replay(myClassMock1, MyClass.class);\n        tested.simpleSingleNew();\n        verify(myClassMock1, MyClass.class);\n    }\n\n    @Test\n    public void testSimpleSingleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce();\n\n        replay(myClassMock1, MyClass.class);\n        tested.simpleSingleNew();\n        verify(myClassMock1, MyClass.class);\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce();\n\n        replay(myClassMock1, MyClass.class);\n        tested.simpleMultipleNew();\n        verify(myClassMock1, MyClass.class);\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_lowerBoundLessThan0() throws Exception {\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        try {\n\n            expectNew(MyClass.class).andReturn(myClassMock1).times(-20, 2);\n            fail(\"Should throw IllegalArgumentException.\");\n        } catch (IllegalArgumentException e) {\n            assertEquals(\"minimum must be >= 0\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_upperBoundLessThan0() throws Exception {\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n        try {\n            expectNew(MyClass.class).andReturn(myClassMock1).times(-1, -2);\n            fail(\"Should throw IllegalArgumentException.\");\n        } catch (IllegalArgumentException e) {\n            assertTrue(e.getMessage().contains(\"<=\"));\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_upperBoundLessThanLowerBound() throws Exception {\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n        try {\n            expectNew(MyClass.class).andReturn(myClassMock1).times(10, 2);\n            fail(\"Should throw IllegalArgumentException.\");\n        } catch (IllegalArgumentException e) {\n            assertTrue(e.getMessage().contains(\"<=\"));\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_OK() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(1, 5);\n\n        replay(myClassMock1, MyClass.class);\n\n        tested.simpleMultipleNew();\n\n        verify(myClassMock1, MyClass.class);\n    }\n\n    @Test\n    public void testSimpleMultipleNew_anyTimes() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).anyTimes();\n\n        replay(myClassMock1, MyClass.class);\n\n        tested.simpleMultipleNew();\n\n        verify(myClassMock1, MyClass.class);\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_notWithinRange() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(5, 7);\n\n        replay(myClassMock1, MyClass.class);\n\n        tested.simpleMultipleNew();\n\n        try {\n            verify(myClassMock1, MyClass.class);\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n\n            assertEquals(\"\\n  Expectation failure on verify:\" + \"\\n    samples.newmocking.MyClass(): expected: between 5 and 7, actual: 3\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void testAlternativeFlow() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        expectNew(DataInputStream.class, new Object[] { null }).andThrow(new RuntimeException(\"error\"));\n\n        replay(ExpectNewDemo.class, DataInputStream.class);\n\n        InputStream stream = tested.alternativePath();\n\n        verify(ExpectNewDemo.class, DataInputStream.class);\n\n        assertNotNull(\"The returned inputstream should not be null.\", stream);\n        assertTrue(\"The returned inputstream should be an instance of ByteArrayInputStream.\", stream instanceof ByteArrayInputStream);\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(4);\n\n        replay(myClassMock1, MyClass.class);\n        try {\n            Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n            verify(myClassMock1, MyClass.class);\n            fail(\"Should throw an exception!.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Expectation failure on verify:\" + \"\\n    samples.newmocking.MyClass(): expected: 4, actual: 3\", e\n                    .getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class);\n        Service serviceMock = createMock(Service.class);\n\n        expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock);\n        expect(expectNewServiceImplMock.useService()).andReturn(expected);\n\n        replay(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verify(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class);\n    }\n\n    @Test\n    public void testNewWithVarArgs() throws Exception {\n        final String firstString = \"hello\";\n        final String secondString = \"world\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        expectNew(VarArgsConstructorDemo.class, firstString, secondString).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getAllMessages()).andReturn(new String[] { firstString, secondString });\n\n        replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        String[] varArgs = tested.newVarArgs(firstString, secondString);\n        assertEquals(2, varArgs.length);\n        assertEquals(firstString, varArgs[0]);\n        assertEquals(secondString, varArgs[1]);\n\n        verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception {\n        final Object object = new Object();\n        try {\n            expectNew(VarArgsConstructorDemo.class, object);\n            fail(\"Should throw ConstructorNotFoundException!\");\n        } catch (ConstructorNotFoundException e) {\n            assertEquals(\"No constructor found in class '\" + VarArgsConstructorDemo.class.getName() + \"' with parameter types: [ \"\n                    + object.getClass().getName() + \" ].\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        Service serviceMock = createMock(Service.class);\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final Service serviceSubTypeInstance = new Service() {\n\n            public String getServiceMessage() {\n                return \"message\";\n            }\n        };\n\n        expectNew(VarArgsConstructorDemo.class, serviceSubTypeInstance, serviceMock).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getAllServices()).andReturn(new Service[] { serviceMock });\n\n        replay(serviceMock, VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock);\n        assertEquals(1, varArgs.length);\n        assertSame(serviceMock, varArgs[0]);\n\n        verify(serviceMock, VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgs() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[] { 42 };\n        final byte[] byteArrayTwo = new byte[] { 17 };\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne });\n\n        replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsAndMatchers() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[] { 42 };\n        final byte[] byteArrayTwo = new byte[] { 17 };\n        expectNew(VarArgsConstructorDemo.class, aryEq(byteArrayOne), aryEq(byteArrayTwo)).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne });\n\n        replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        byte[][] varArgs = tested.newVarArgsWithMatchers();\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[] { 17 };\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo });\n\n        replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[] { 42 };\n        final byte[] byteArrayTwo = null;\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne });\n\n        replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[] { 42 };\n        final byte[] byteArrayThree = null;\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo, byteArrayThree).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo });\n\n        replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = null;\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo });\n\n        replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock);\n    }\n\n    @Test\n    public void testNewWithWrongArgument() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class);\n        Service serviceMock = createMock(Service.class);\n\n        expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock);\n        expect(expectNewServiceImplMock.useService()).andReturn(expected);\n\n        replay(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class);\n\n        try {\n            assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes));\n            verify(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class);\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\n                    \"\\n  Unexpected constructor call samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 4 (int)):\"\n                            + \"\\n    samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 2 (int)): expected: 1, actual: 0\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void testExpectNewButNoNewCallWasMade() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).once();\n\n        replay(myClassMock1, MyClass.class);\n        try {\n            tested.makeDate();\n            verify(myClassMock1, MyClass.class);\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertTrue(e.getMessage().contains(MyClass.class.getName() + \"(): expected: 1, actual: 0\"));\n        }\n    }\n\n    @Test\n    public void canDefineSeveralMockResultForNew() throws Exception {\n\n        final Target expectedTarget = new Target(UNKNOWN_TARGET_NAME, UNKNOWN_TARGET_ID);\n\n        expectNew(Target.class, TARGET_NAME, TARGET_ID).andThrow(new CreationException());\n        expectNew(Target.class, \"Unknown\",-1).andReturn(expectedTarget);\n\n        replay(Target.class);\n\n        Target actualTarget = new ExpectNewDemo().createTarget(new ITarget() {\n            @Override\n            public int getId() {\n                return TARGET_ID;\n            }\n\n            @Override\n            public String getName() {\n                return TARGET_NAME;\n            }\n        });\n        assertThat(actualTarget).isEqualToComparingFieldByField(expectedTarget);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.expectnew;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\n\nimport java.io.DataInputStream;\n\n/**\n * Test class to demonstrate new instance mocking using expectNew(..).\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class })\npublic class ExpectNewDemoTest extends ExpectNewCases {\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java",
    "content": "package samples.junit4.expectnew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewOfFinalSystemClassDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ExpectNewOfFinalSystemClassDemo.class)\npublic class ExpectNewOfFinalSystemClassTest {\n\n    @Test\n    public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception {\n        String mock = createMock(String.class);\n\n        expectNew(String.class, \"My String\").andReturn(mock);\n        expect(mock.charAt(0)).andReturn('o');\n\n        replayAll();\n        assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar());\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/expectnew/MockDateTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.expectnew;\n\nimport junit.framework.Assert;\nimport org.easymock.EasyMock;\nimport org.easymock.internal.MocksControl;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.PowerMock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\n\nimport java.util.Date;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { ExpectNewDemo.class })\npublic class MockDateTest {\n\n\t@Test\n\tpublic void testMockDate() throws Exception {\n\t\tDate someDate = new Date();\n\t\tDate date = PowerMock.createMock(Date.class);\n\t\tEasyMock.expect(date.after(someDate)).andReturn(false);\n\n\t\tPowerMock.replay(date);\n\n\t\tdate.after(someDate);\n\n\t\tPowerMock.verify(date);\n\t}\n\n\t@Test\n\tpublic void testMockDateWithEasyMock() throws Exception {\n\t\tDate someDate = new Date();\n\t\tMocksControl c = (MocksControl) org.easymock.EasyMock.createControl();\n\t\tDate date = c.createMock(Date.class);\n\t\tEasyMock.expect(date.after(someDate)).andReturn(false);\n\n\t\tPowerMock.replay(date);\n\n\t\tdate.after(someDate);\n\n\t\tPowerMock.verify(date);\n\t}\n\n\t@Test(expected = IllegalStateException.class)\n\tpublic void testMockDateWithEasyMockFails() {\n\t\tDate someDate = new Date();\n\t\tMocksControl c = (MocksControl) org.easymock.EasyMock.createControl();\n\t\tDate date = c.createMock(null, Date.class, null);\n\t\tEasyMock.expect(date.after(someDate)).andReturn(false);\n\t\tAssert.fail(\"EasyMock with no methods mocked should not be possible to mock\");\n\t}\n\n\t@Test\n\tpublic void testExpectNewDate() throws Exception {\n\t\tDate someDate = new Date();\n\t\tlong time = someDate.getTime();\n\t\tPowerMock.expectNew(Date.class).andReturn(someDate);\n\n\t\tPowerMock.replay(Date.class);\n\n\t\tAssert.assertEquals(time, new ExpectNewDemo().makeDate().getTime());\n\n\t\tPowerMock.verify(Date.class);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperDemoTest.java",
    "content": "package samples.junit4.expectnew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.exceptions.TooManyConstructorsFoundException;\nimport samples.expectnew.PrimitiveAndWrapperDemo;\n\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.fail;\nimport static org.junit.matchers.JUnitMatchers.containsString;\nimport static org.powermock.api.easymock.PowerMock.createMockAndExpectNew;\n\n/**\n * Unit test for the {@link PrimitiveAndWrapperDemo} class.\n */\n@RunWith(PowerMockRunner.class)\npublic class PrimitiveAndWrapperDemoTest {\n\n\t@Test\n\tpublic void testWhenConstructorCannotBeDetermined() throws Exception {\n\t\ttry {\n\t\t\tcreateMockAndExpectNew(PrimitiveAndWrapperDemo.class, 2);\n\t\t\tfail(\"Should throw TooManyConstructorsFoundException\");\n\t\t} catch (TooManyConstructorsFoundException e) {\n\t\t\tassertThat(e.getMessage(), containsString(\"Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\"\n                    + \"\\nMatching constructors in class samples.expectnew.PrimitiveAndWrapperDemo were:\\n\"));\n            assertThat(e.getMessage(), containsString(\"samples.expectnew.PrimitiveAndWrapperDemo( java.lang.Integer.class )\\n\"));\n            assertThat(e.getMessage(), containsString(\"samples.expectnew.PrimitiveAndWrapperDemo( int.class )\\n\"));\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testWrapperConstructor() throws Exception {\n\t\tcreateMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class<?>[] { Integer.class }, 2);\n\t}\n\n\t@Test\n\tpublic void testPrimitiveConstructor() throws Exception {\n\t\tcreateMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class<?>[] { int.class }, 2);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperUserTest.java",
    "content": "package samples.junit4.expectnew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.PrimitiveAndWrapperDemo;\nimport samples.expectnew.PrimitiveAndWrapperUser;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Unit test for the {@link PrimitiveAndWrapperUser} class.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PrimitiveAndWrapperUser.class)\npublic class PrimitiveAndWrapperUserTest {\n\n\t@Test\n\tpublic void testNewWithStrictMocking_ok() throws Exception {\n\t\tPrimitiveAndWrapperDemo mock1 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class<?>[] { Integer.class }, 42);\n\t\tPrimitiveAndWrapperDemo mock2 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class<?>[] { int.class }, 21);\n\n\t\texpect(mock1.getMyInt()).andReturn(10);\n\t\texpect(mock2.getMyInt()).andReturn(21);\n\n\t\treplayAll();\n\n\t\tassertEquals(31, new PrimitiveAndWrapperUser().useThem());\n\n\t\tverifyAll();\n\t}\n\n\t@Test(expected = AssertionError.class)\n\tpublic void testNewWithStrictMocking_notOk() throws Exception {\n\t\tPrimitiveAndWrapperDemo mock2 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class<?>[] { int.class }, 21);\n\t\tPrimitiveAndWrapperDemo mock1 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class<?>[] { Integer.class }, 42);\n\n\t\texpect(mock1.getMyInt()).andReturn(10);\n\t\texpect(mock2.getMyInt()).andReturn(21);\n\n\t\treplayAll();\n\n\t\tassertEquals(31, new PrimitiveAndWrapperUser().useThem());\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void testNewWithNiceMocking() throws Exception {\n\t\tPrimitiveAndWrapperDemo mock = createNiceMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class<?>[] { Integer.class }, 42);\n\t\texpect(mock.getMyInt()).andReturn(2);\n\n\t\treplayAll();\n\n\t\tassertEquals(2, new PrimitiveAndWrapperUser().useThem());\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/expectvoid/ExpectVoidDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.expectvoid;\n\nimport org.easymock.EasyMock;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.expectvoid.ExpectVoidDemo;\n\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ExpectVoidDemo.class)\npublic class ExpectVoidDemoTest {\n\n\t@Test\n\tpublic void testInvokeAPrivateVoidMethod() throws Exception {\n\t\tfinal String methodToMock = \"privateInvoke\";\n\t\tExpectVoidDemo tested = createPartialMock(ExpectVoidDemo.class, methodToMock);\n\n\t\tfinal int expected = 112;\n\n\t\texpectPrivate(tested, methodToMock, expected).times(1);\n\n\t\treplay(tested);\n\n\t\ttested.invokeAPrivateVoidMethod(expected);\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testInvokeAPrivateVoidMethod_usingPowerMockExpectLastCall()\n\t\t\tthrows Exception {\n\t\tfinal String methodToMock = \"privateInvoke\";\n\t\tExpectVoidDemo tested = createPartialMock(ExpectVoidDemo.class, methodToMock);\n\n\t\tfinal int expected = 112;\n\n\t\tWhitebox.invokeMethod(tested, methodToMock, expected);\n\t\texpectLastCall().times(1);\n\n\t\treplay(tested);\n\n\t\ttested.invokeAPrivateVoidMethod(expected);\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testInvokeAPrivateVoidMethod_usingEasyMockExpectLastCall()\n\t\t\tthrows Exception {\n\t\tfinal String methodToMock = \"privateInvoke\";\n\t\tExpectVoidDemo tested = createPartialMock(ExpectVoidDemo.class, methodToMock);\n\n\t\tfinal int expected = 112;\n\n\t\tWhitebox.invokeMethod(tested, methodToMock, expected);\n\t\tEasyMock.expectLastCall();\n\n\t\treplay(tested);\n\n\t\ttested.invokeAPrivateVoidMethod(expected);\n\n\t\tverify(tested);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/FinalDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.finalmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate non-static final mocking.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class FinalDemoTest {\n\n\t@Test\n\tpublic void testSay() throws Exception {\n\t\tFinalDemo tested = createMock(FinalDemo.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.say(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\n\t}\n\n\t@Test\n\tpublic void testSayFinalNative() throws Exception {\n\t\tFinalDemo tested = createMock(FinalDemo.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.sayFinalNative(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.sayFinalNative(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.sayFinalNative(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/MockingOfInstanceMethodsInFinalSystemClassTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.finalmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate non-static final mocking of instance methods in\n * system classes.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(MockingOfInstanceMethodsInFinalSystemClassTest.class)\npublic class MockingOfInstanceMethodsInFinalSystemClassTest {\n\n\t@Test\n\tpublic void assertThatMockingOfInstanceMethodsInFinalSystemClassesWorks() throws Exception {\n\t\tLong tested = createMock(Long.class);\n\t\texpect(tested.longValue()).andReturn(22L);\n\t\treplayAll();\n\n\t\tassertEquals(22L, tested.longValue());\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertThatMockingOfInstanceMethodsInStringWorks() throws Exception {\n\t\tString tested = createMock(String.class);\n\t\texpect(tested.charAt(2)).andReturn('A');\n\t\treplayAll();\n\n\t\tassertEquals('A', tested.charAt(2));\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertThatPartialMockingOfInstanceMethodsInFinalSystemClassesWhenNotInvokingConstructorWorks()\n\t\t\tthrows Exception {\n\t\tLong tested = createPartialMock(Long.class, \"doubleValue\");\n\t\texpect(tested.doubleValue()).andReturn(54d);\n\t\treplayAll();\n\n\t\tassertEquals(0, tested.longValue());\n\t\tassertEquals(54d, tested.doubleValue(), 0.0d);\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void assertThatPartialMockingOfInstanceMethodsInFinalSystemClassesWhenNotInvokingNonDefaultConstructorWorks()\n\t\t\tthrows Exception {\n\t\tLong tested = createPartialMock(Long.class, new String[] { \"doubleValue\" }, 27L);\n\t\texpect(tested.doubleValue()).andReturn(54d);\n\t\treplayAll();\n\n\t\tassertEquals(27L, tested.longValue());\n\t\tassertEquals(54d, tested.doubleValue(), 0.0d);\n\n\t\tverifyAll();\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/NoDuplicateTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.finalmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * This test demonstrates that the issue at\n * http://code.google.com/p/powertest/issues/detail?id=63 is solved.\n * \n * <p>\n * The bug was that if there were only one test case and the\n * {@code @PrepareForTest} annotation was placed at the test method instead\n * of the class the PowerMock JUnit runner would detect an extra test case.\n * \n */\n@RunWith(PowerMockRunner.class)\npublic class NoDuplicateTest {\n\n\t@Test\n\t@PrepareForTest(FinalDemo.class)\n\tpublic void assertThatPrepareForTestAnnotationAtMethodLevelButNotClassLevelWorks() throws Exception {\n\t\tFinalDemo tested = createMock(FinalDemo.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.say(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/hashcode/PowerMockUsesIdentityHashMapToStoreMocks.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.hashcode;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.hashcode.HashCodeInitializedInCtor;\n\nimport static org.powermock.api.easymock.PowerMock.createMock;\n\n@RunWith(PowerMockRunner.class)\npublic class PowerMockUsesIdentityHashMapToStoreMocks {\n\n     @Test\n     public void storesObjectsToAutomaticallyReplayAndVerifyToAnIdentityHashMap()throws Exception {\n       createMock(HashCodeInitializedInCtor.class);\n     }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/interfacefieldchange/ChangeValueOfStaticFinalFieldInInterfacesDefect.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit4.interfacefieldchange;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.interfacefieldchange.InterfaceWithStaticFinalField;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * This test asserts that it's possible for PowerMock to modify static final\n * fields in Interfaces.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { InterfaceWithStaticFinalField.class })\npublic class ChangeValueOfStaticFinalFieldInInterfacesDefect {\n\n\t@Test\n\tpublic void assertThatStaticFinalFieldValuesInInterfacesAreChangable() throws Exception {\n\t\tfinal String value = \"new value\";\n\t\tWhitebox.setInternalState(InterfaceWithStaticFinalField.class, value);\n\t\tassertEquals(value, Whitebox.getInternalState(InterfaceWithStaticFinalField.class, String.class));\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/java/MockClassesInsideJavaPackage.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.java;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.java.ClassInsideJavaPackage;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ClassInsideJavaPackage.class)\npublic class MockClassesInsideJavaPackage {\n\n    @Test\n    public void allowsMockingOfClassesInsidePackageContainingJava() {\n        ClassInsideJavaPackage mock = createMock(ClassInsideJavaPackage.class);\n        expect(mock.mockMe()).andReturn(\"mocked\");\n\n        replayAll();\n\n        assertEquals(\"mocked\", mock.mockMe());\n\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/largemethod/LargeMethodTest.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.junit4.largemethod;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.largemethod.MethodExceedingJvmLimit;\n\nimport static junit.framework.Assert.assertEquals;\nimport static junit.framework.Assert.assertNull;\nimport static junit.framework.Assert.assertSame;\nimport static junit.framework.Assert.assertTrue;\nimport static junit.framework.Assert.fail;\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.method;\nimport static org.powermock.api.easymock.PowerMock.mockStatic;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.suppress;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(MethodExceedingJvmLimit.class)\npublic class LargeMethodTest {\n\n    @Test\n    public void largeMethodShouldBeOverridden() {\n        try {\n            MethodExceedingJvmLimit.init();\n            fail(\"Method should be overridden and exception should be thrown\");\n        } catch (Exception e) {\n            assertSame(IllegalAccessException.class, e.getClass());\n            assertTrue(e.getMessage().contains(\"Method was too large and after instrumentation exceeded JVM limit\"));\n        }\n    }\n\n    @Test\n    public void largeMethodShouldBeAbleToBeSuppressed() {\n        suppress(method(MethodExceedingJvmLimit.class, \"init\"));\n        assertNull(\"Suppressed method should return: null\", MethodExceedingJvmLimit.init());\n    }\n\n    @Test\n    public void largeMethodShouldBeAbleToBeMocked() {\n        mockStatic(MethodExceedingJvmLimit.class);\n        expect(MethodExceedingJvmLimit.init()).andReturn(\"ok\");\n        replayAll();\n        assertEquals(\"Mocked method should return: ok\", \"ok\", MethodExceedingJvmLimit.init());\n    }\n\n    @Test(expected = IllegalStateException.class)\n    public void largeMethodShouldBeAbleToBeMockedAndThrowException() {\n        mockStatic(MethodExceedingJvmLimit.class);\n        expect(MethodExceedingJvmLimit.init()).andThrow(new IllegalStateException());\n        replayAll();\n        MethodExceedingJvmLimit.init();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/misc/PrivateInnerInterfacesInTestClassTest.java",
    "content": "package samples.junit4.misc;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.assertEquals;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { PrivateInnerInterfacesInTestClassTest.class })\npublic class PrivateInnerInterfacesInTestClassTest {\n\n\t@Test\n\tpublic void privateInterfacesCanBeLoadedAndBytcodeManipulatedByPowerMock() throws Exception {\n\t\tInnerInterface innerInterface = new InnerInterface() {\n\t\t\tpublic String aMethod() {\n\t\t\t\treturn \"ok\";\n\t\t\t}\n\t\t};\n\t\tassertEquals(\"ok\", innerInterface.aMethod());\n\t}\n\n\tprivate interface InnerInterface {\n\t\tString aMethod();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyUsageExampleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.mockpolicy;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.mockpolicy.ResultCalculator;\nimport samples.mockpolicy.SomeClassWithAMethod;\n\nimport java.lang.reflect.Method;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * A simple example of a mock policy that stubs out a method call.\n */\n@RunWith(PowerMockRunner.class)\n@MockPolicy(MockPolicyExample.class)\npublic class MockPolicyUsageExampleTest {\n\n\t@Test\n\tpublic void exampleOfStubbingOutCallsInParentClass() throws Exception {\n\t\tSomeClassWithAMethod tested = new SomeClassWithAMethod();\n\t\tassertEquals(8.0d, tested.getResult(), 0.0d);\n\t}\n}\n\nclass MockPolicyExample implements PowerMockPolicy {\n\t@Override\n\tpublic void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {\n\t\tsettings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName());\n\t}\n\n\t@Override\n\tpublic void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {\n\t\tMethod calculateMethod = Whitebox.getMethod(ResultCalculator.class, \"calculate\");\n\t\tsettings.stubMethod(calculateMethod, 4d);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithExpectationsTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit4.mockpolicy;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.mockpolicy.ResultCalculator;\nimport samples.mockpolicy.SimpleClassWithADependency;\n\nimport java.lang.reflect.Method;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@MockPolicy(MockPolicyExpectationsExample.class)\npublic class MockPolicyWithExpectationsTest {\n\n\t@Test\n\tpublic void mockPolicyWithExpectationsWorks() throws Exception {\n\t\tfinal SimpleClassWithADependency tested = new SimpleClassWithADependency();\n\t\tWhitebox.setInternalState(tested, new ResultCalculator(5));\n\t\t\n\t\tassertEquals(2.0, tested.getResult(), 0.0);\n\t\t\n\t\tverifyAll();\n\t}\n}\n\nclass MockPolicyExpectationsExample implements PowerMockPolicy {\n\t@Override\n\tpublic void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {\n\t\tsettings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName());\n\t}\n\n\t@Override\n\tpublic void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {\n\t\tfinal ResultCalculator calculatorMock = createMock(ResultCalculator.class);\n\t\texpect(calculatorMock.calculate()).andReturn(2.0);\n\n\t\treplay(calculatorMock);\n\n\t\tMethod calculateMethod = Whitebox.getMethod(ResultCalculator.class, \"calculate\");\n\t\tsettings.stubMethod(calculateMethod, calculatorMock.calculate());\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithInvocationHandlerTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit4.mockpolicy;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.mockpolicy.ResultCalculator;\nimport samples.mockpolicy.SimpleClassWithADependency;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\n\n@RunWith(PowerMockRunner.class)\n@MockPolicy(MockPolicyInvocationHandlerExample.class)\npublic class MockPolicyWithInvocationHandlerTest {\n\n\t@Test\n    public void mockPolicyWithInvocationHandlerWorks() {\n\t\tfinal SimpleClassWithADependency tested = new SimpleClassWithADependency();\n\t\tWhitebox.setInternalState(tested, new ResultCalculator(0));\n\n\t\tassertEquals(1.0, tested.getResult(), 0.0);\n\n\t\tverifyAll();\n\t}\n}\n\nclass MockPolicyInvocationHandlerExample implements PowerMockPolicy {\n\t@Override\n\tpublic void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {\n\t\tsettings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName());\n\t}\n\n\t@Override\n\tpublic void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {\n        settings.proxyMethod(method(ResultCalculator.class, \"calculate\"), new InvocationHandler() {\n\n\t\t\t@Override\n\t\t\tpublic Object invoke(Object object, Method method, Object[] args) throws Throwable {\n\t\t\t\tfinal double result = (Double) method.invoke(object, args);\n\t\t\t\treturn result + 1.0;\n\t\t\t}\n\t\t});\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkMockPolicy.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.mockpolicy.frameworkexample;\n\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.reflect.Whitebox;\nimport samples.mockpolicy.frameworkexample.NativeResult;\nimport samples.mockpolicy.frameworkexample.SimpleFramework;\n\nimport java.lang.reflect.Method;\n\npublic class SimpleFrameworkMockPolicy implements PowerMockPolicy {\n\n\tpublic static final String NATIVE_RESULT_VALUE = \"result\";\n\n\t@Override\n\tpublic void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {\n\t\tsettings.addStaticInitializersToSuppress(\"samples.mockpolicy.frameworkexample.SimpleFramework\");\n\t}\n\n\t@Override\n\tpublic void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {\n\t\tfinal Method doNativeStuffMethod = Whitebox.getMethod(SimpleFramework.class, String.class);\n\t\tNativeResult nativeResult = new NativeResult(NATIVE_RESULT_VALUE);\n\t\tsettings.stubMethod(doNativeStuffMethod, nativeResult);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkUserTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.mockpolicy.frameworkexample;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.mockpolicy.frameworkexample.SimpleFrameworkUser;\n\nimport static org.junit.Assert.assertEquals;\n\n@RunWith(PowerMockRunner.class)\n@MockPolicy(SimpleFrameworkMockPolicy.class)\npublic class SimpleFrameworkUserTest {\n\n\t@Test\n\tpublic void testPerformComplexOperation() {\n\t\tSimpleFrameworkUser tested = new SimpleFrameworkUser();\n\t\tassertEquals(SimpleFrameworkMockPolicy.NATIVE_RESULT_VALUE, tested.performComplexOperation(\"some complex stuff\"));\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/multireplayverify/MultiReplayVerifyTest.java",
    "content": "package samples.junit4.multireplayverify;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Asserts that it's ok the manually replay a mock and then use replayAll(). The\n * same regards verify and verifyAll.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ExpectNewDemo.class)\npublic class MultiReplayVerifyTest {\n\n\t@Test\n\tpublic void replyFollowedByReplayAllIsAllowed() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\t\tMyClass myClassMock = createMock(MyClass.class);\n\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\n\t\tString expected = \"Hello altered World\";\n\t\texpect(myClassMock.getMessage()).andReturn(\"Hello altered World\");\n\n\t\treplay(MyClass.class);\n\t\treplayAll();\n\n\t\tString actual = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void verifyFollowedByVerifyAllIsAllowed() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\t\tMyClass myClassMock = createMock(MyClass.class);\n\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\n\t\tString expected = \"Hello altered World\";\n\t\texpect(myClassMock.getMessage()).andReturn(\"Hello altered World\");\n\n\t\treplayAll();\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(MyClass.class);\n\t\tverifyAll();\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/nativemocking/NativeMockingSampleTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.nativemocking;\n\nimport org.junit.Test;\nimport samples.nativemocking.NativeMockingSample;\nimport samples.nativemocking.NativeService;\n\nimport static org.easymock.EasyMock.*;\nimport static org.junit.Assert.assertEquals;\n\n/**\n * This test demonstrates that it's possible to mock native methods using plain\n * EasyMock class extensions.\n */\npublic class NativeMockingSampleTest {\n\n\t@Test\n\tpublic void testMockNative() throws Exception {\n\t\tNativeService nativeServiceMock = createMock(NativeService.class);\n\t\tNativeMockingSample tested = new NativeMockingSample(nativeServiceMock);\n\n\t\tfinal String expectedParameter = \"question\";\n\t\tfinal String expectedReturnValue = \"answer\";\n\t\texpect(nativeServiceMock.invokeNative(expectedParameter)).andReturn(expectedReturnValue);\n\n\t\treplay(nativeServiceMock);\n\n\t\tassertEquals(expectedReturnValue, tested.invokeNativeMethod(expectedParameter));\n\n\t\tverify(nativeServiceMock);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/newmocking/StupidNewTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.newmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.newmocking.MyClass;\nimport samples.newmocking.StupidNew;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate new instance mocking.\n * \n * @author Johan Haleby\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MyClass.class, StupidNew.class })\npublic class StupidNewTest {\n\n\t@Test\n\tpublic void testGetMessage() throws Exception {\n\t\tStupidNew tested = new StupidNew();\n\n\t\tMyClass myClassMock = createMockAndExpectNew(MyClass.class);\n\n\t\tString expected = \"Hello altered World\";\n\t\texpect(myClassMock.getMessage()).andReturn(\"Hello altered World\");\n\t\treplay(myClassMock, MyClass.class);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(myClassMock, MyClass.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testGetMessageWithArgument() throws Exception {\n\t\tStupidNew tested = new StupidNew();\n\n\t\tMyClass myClassMock = createMockAndExpectNew(MyClass.class);\n\n\t\tString expected = \"Hello altered World\";\n\t\texpect(myClassMock.getMessage(\"test\")).andReturn(\"Hello altered World\");\n\t\treplay(myClassMock, MyClass.class);\n\n\t\tString actual = tested.getMessageWithArgument();\n\n\t\tverify(myClassMock, MyClass.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testInvokeVoidMethod() throws Exception {\n\t\tStupidNew tested = new StupidNew();\n\n\t\tMyClass myClassMock = createMockAndExpectNew(MyClass.class);\n\t\tmyClassMock.voidMethod();\n\t\texpectLastCall().times(1);\n\n\t\treplay(myClassMock, MyClass.class);\n\n\t\ttested.invokeVoidMethod();\n\n\t\tverify(myClassMock, MyClass.class);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/nice/NiceDemoTest.java",
    "content": "package samples.junit4.nice;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.nice.NiceDemo;\n\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * This is a simple test case for the {@link NiceDemo} class that demonstrates\n * that strict method mocking works.\n * \n */\n@RunWith(PowerMockRunner.class)\npublic class NiceDemoTest {\n\n\t@Test\n\tpublic void testCallAThenB_noExpectations() throws Exception {\n\t\tNiceDemo tested = createNicePartialMock(NiceDemo.class, \"A\", \"B\");\n\n\t\treplay(tested);\n\n\t\ttested.callAThenB();\n\n\t\tverify(tested);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/noannotation/NoAnnotationUsageTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.noannotation;\n\nimport junit.framework.TestCase;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticandinstance.StaticAndInstanceDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test case that demonstrates the ability to run test cases not annotated with\n * {@link Test} when extending from {@link TestCase} using JUnit 4.4.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class NoAnnotationUsageTest extends TestCase {\n\n\tpublic void testGetMessage() throws Exception {\n\t\tmockStaticPartial(StaticAndInstanceDemo.class, \"getStaticMessage\");\n\n\t\tStaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, \"getPrivateMessage\");\n\n\t\tfinal String staticExpected = \"a static message\";\n\t\texpect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected);\n\t\tfinal String privateExpected = \"A private message \";\n\t\texpectPrivate(tested, \"getPrivateMessage\").andReturn(privateExpected);\n\n\t\treplay(tested);\n\t\treplay(StaticAndInstanceDemo.class);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(tested);\n\t\tverify(StaticAndInstanceDemo.class);\n\n\t\tassertEquals(privateExpected + staticExpected, actual);\n\t}\n\n\tpublic void testGetMessage2() throws Exception {\n\t\tmockStaticPartial(StaticAndInstanceDemo.class, \"getStaticMessage\");\n\n\t\tStaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, \"getPrivateMessage\");\n\n\t\tfinal String staticExpected = \"a static message\";\n\t\texpect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected);\n\t\tfinal String privateExpected = \"A private message \";\n\t\texpectPrivate(tested, \"getPrivateMessage\").andReturn(privateExpected);\n\n\t\treplay(tested);\n\t\treplay(StaticAndInstanceDemo.class);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(tested);\n\t\tverify(StaticAndInstanceDemo.class);\n\n\t\tassertEquals(privateExpected + staticExpected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java",
    "content": "package samples.junit4.noannotation;\n\nimport junit.framework.TestCase;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n@RunWith(PowerMockRunner.class)\npublic class SetUpAndTearDownWhenExtendingTestCaseTest extends TestCase {\n\tprivate static final String INITIAL_MESSAGE = \"\";\n\tprivate static final String SET_UP_MESSAGE = \"setUp\";\n\tprivate static final String TEST_MESSAGE = \"test\";\n\n\tprivate static String CURRENT_MESSAGE = INITIAL_MESSAGE;\n\n\t@Override\n\tprotected void setUp() throws Exception {\n\t\tassertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE);\n\t\tCURRENT_MESSAGE = SET_UP_MESSAGE;\n\t}\n\n\t@Override\n\tprotected void tearDown() throws Exception {\n\t\tassertEquals(TEST_MESSAGE, CURRENT_MESSAGE);\n\t}\n\n\tpublic void testSomething() throws Exception {\n\t\tassertEquals(SET_UP_MESSAGE, CURRENT_MESSAGE);\n\t\tCURRENT_MESSAGE = TEST_MESSAGE;\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenNotExtendingTestCaseTest.java",
    "content": "package samples.junit4.noannotation;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\n\n@RunWith(PowerMockRunner.class)\npublic class SetUpAndTearDownWhenNotExtendingTestCaseTest {\n\tprivate static final String INITIAL_MESSAGE = \"\";\n\tprivate static String CURRENT_MESSAGE = INITIAL_MESSAGE;\n\n\tpublic void setUp() throws Exception {\n\t\tfail(\"Should not call setUp\");\n\t}\n\n\tpublic void tearDown() throws Exception {\n\t\tfail(\"Should not call tearDown\");\n\t}\n\n\t@Test\n\tpublic void testSomething() throws Exception {\n\t\tassertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest.java",
    "content": "package samples.junit4.noannotation;\n\nimport junit.framework.TestCase;\nimport org.junit.Before;\n\npublic class SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest extends TestCase {\n\n    private int state = 0;\n\n    @Before\n    @Override\n    public void setUp() throws Exception {\n        state++;\n    }\n\n    public void testSetupMethodIsOnlyCalledOnceWhenExtendingFromTestCase() throws Exception {\n        assertEquals(1, state);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/noannotation/StringConstructorWorksWhenExtendingTestCase.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.noannotation;\n\nimport junit.framework.TestCase;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Demonstrates that the PowerMock JUnit runner works with single-arg string\n * constructor. Asserts that issue <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=174\">174</a> is\n * fixed.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticService.class, StaticHelper.class })\npublic class StringConstructorWorksWhenExtendingTestCase extends TestCase {\n\n    public StringConstructorWorksWhenExtendingTestCase(String name) {\n        super(name);\n    }\n\n    public void testMockingStaticMethodWorksWhenStringArgConstructor() throws Exception {\n        mockStatic(StaticService.class);\n        String expected = \"Hello altered World\";\n        expect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n        replay(StaticService.class);\n\n        String actual = StaticService.say(\"hello\");\n\n        verify(StaticService.class);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n\n        // Singleton still be mocked by now.\n        try {\n            StaticService.say(\"world\");\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected method call StaticService.say(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/overloading/MethodWithSameNameButDifferentDefinitionTypeTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.overloading;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.classhierarchy.ChildA;\nimport samples.classhierarchy.Parent;\nimport samples.overloading.StaticAndInstanceMethodWithSameName;\nimport samples.overloading.StaticAndInstanceMethodWithSameNameUser;\n\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Demonstrates that PowerMock correctly methods that seam to be overloaded but\n * differ because one is static and one is instance.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticAndInstanceMethodWithSameNameUser.class, StaticAndInstanceMethodWithSameName.class })\npublic class MethodWithSameNameButDifferentDefinitionTypeTest {\n\n    @Test\n    public void mockGatewayCanInvokeInstanceMethodWhenClassContainsStaticAndInstanceMethodWithSameName() throws Exception {\n        final ChildA object = createMock(ChildA.class);\n        StaticAndInstanceMethodWithSameName mock = createMock(StaticAndInstanceMethodWithSameName.class);\n\n        expectNew(ChildA.class).andReturn(object);\n        mock.overloaded((Parent) object);\n        expectLastCall().once();\n\n        replayAll();\n\n        new StaticAndInstanceMethodWithSameNameUser().performInstaceInvocation(mock);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockGatewayCanInvokeStaticMethodWhenClassContainsStaticAndInstanceMethodWithSameName() throws Exception {\n        final Parent object = createMock(ChildA.class);\n\n        mockStatic(StaticAndInstanceMethodWithSameName.class);\n        expectNew(ChildA.class).andReturn((ChildA) object);\n        StaticAndInstanceMethodWithSameName.overloaded((ChildA) object);\n        expectLastCall().once();\n\n        replayAll();\n\n        new StaticAndInstanceMethodWithSameNameUser().performStaticInvocation();\n\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/overloading/OverloadingDemoTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.overloading;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.classhierarchy.ChildA;\nimport samples.classhierarchy.Parent;\nimport samples.overloading.OverloadedMethodsExample;\nimport samples.overloading.OverloadingDemo;\n\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Demonstrates that PowerMock correctly invoke overloaded methods from the\n * MockGateway.\n * href=\"http://code.google.com/p/powermock/issues/detail?id=229\">229</a> is\n * solved.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({ OverloadedMethodsExample.class, OverloadingDemo.class })\npublic class OverloadingDemoTest {\n\n\t@Test\n\tpublic void mockGatewayFindsBestOverloadedMethodCandidateWhenOnlyOneArgument() throws Exception {\n\t\tfinal Parent object = createMock(ChildA.class);\n\n\t\tmockStatic(OverloadedMethodsExample.class);\n\n\t\tOverloadedMethodsExample.overloadedMethodWithOneArgument(object);\n\t\texpectLastCall().once();\n\n\t\texpectNew(ChildA.class).andReturn((ChildA) object);\n\n\t\treplayAll();\n\n\t\tfinal OverloadingDemo demo = new OverloadingDemo();\n\t\tdemo.performSingleOverloadedArgumentTest();\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void mockGatewayFindsBestOverloadedMethodCandidateWhenBothArgumentSame() throws Exception {\n\t\tfinal Parent child = createMock(ChildA.class);\n\n\t\tmockStatic(OverloadedMethodsExample.class);\n\n\t\tOverloadedMethodsExample.overloadedMethodWithTwoArguments(child, child);\n\t\texpectLastCall().once();\n\n\t\texpectNew(ChildA.class).andReturn((ChildA) child).times(2);\n\n\t\treplayAll();\n\n\t\tfinal OverloadingDemo demo = new OverloadingDemo();\n\t\tdemo.performMethodOverloadTestWhenBothArgumentSame();\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void mockGatewayFindsBestOverloadedMethodCandidateWhenOneArgumentSameAndOneDifferent() throws Exception {\n\t\tfinal Parent child = createMock(ChildA.class);\n\t\tfinal Parent parent = createMock(Parent.class);\n\n\t\tmockStatic(OverloadedMethodsExample.class);\n\n\t\tOverloadedMethodsExample.overloadedMethodWithTwoArguments(parent, child);\n\t\texpectLastCall().once();\n\n\t\texpectNew(ChildA.class).andReturn((ChildA) child);\n\t\texpectNew(Parent.class).andReturn(parent);\n\n\t\treplayAll();\n\n\t\tfinal OverloadingDemo demo = new OverloadingDemo();\n\t\tdemo.performMethodOverloadTestWithOneArgumentSameAndOneDiffernt();\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.partialmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport samples.partialmocking.MockSelfDemo;\nimport samples.partialmocking.MockSelfWithNoDefaultConstructorDemo;\n\nimport java.sql.Connection;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(MockSelfDemo.class)\npublic class MockSelfDemoTest {\n\n    private MockSelfDemo tested;\n\n    @Test\n    public void testMockMultiple_ok() throws Exception {\n        tested = createPartialMock(MockSelfDemo.class, \"aMethod2\", \"getString\");\n\n        tested.aMethod2();\n        expectLastCall().times(1);\n\n        final String expected = \"Hello altered world\";\n        expect(tested.getString(\"world\")).andReturn(expected);\n\n        replay(tested);\n\n        String actual = tested.aMethod();\n\n        verify(tested);\n\n        assertEquals(\"Result ought to be \\\"Hello altered world\\\".\", expected, actual);\n    }\n\n    @Test\n    public void testMockMultiple_sameName() throws Exception {\n        tested = createPartialMock(MockSelfDemo.class, \"getString\");\n\n        final String firstString = \"A message: \";\n        expectPrivate(tested, \"getString\").andReturn(firstString);\n\n        final String secondString = \"altered world\";\n        expect(tested.getString(\"world2\")).andReturn(secondString);\n        final String expected = firstString + secondString;\n\n        replay(tested);\n\n        String actual = tested.getTwoStrings();\n\n        verify(tested);\n\n        assertEquals(\"Result ought to be \\\"A message:Hello altered world\\\".\", expected, actual);\n    }\n\n    @Test\n    public void testMockSingleMethod() throws Exception {\n        tested = createPartialMock(MockSelfDemo.class, \"timesTwo\", int.class);\n\n        final int expectedInt = 2;\n        final int expectedInteger = 8;\n        expect(tested.timesTwo(4)).andReturn(expectedInt);\n\n        replay(tested);\n\n        int actualInt = tested.timesTwo(4);\n        int actualInteger = tested.timesTwo(new Integer(4));\n\n        verify(tested);\n\n        assertEquals(expectedInt, actualInt);\n        assertEquals(expectedInteger, actualInteger);\n    }\n\n    @Test\n    public void testMockAllExcept_parametersDefined() throws Exception {\n        tested = createPartialMockForAllMethodsExcept(MockSelfDemo.class, \"getString2\", String.class);\n\n        final String expected = \"Hello altered world\";\n        expect(tested.getString2()).andReturn(expected);\n\n        replay(tested);\n        assertEquals(expected, tested.getString2());\n        assertEquals(\"Hello string\", tested.getString2(\"string\"));\n        verify(tested);\n    }\n\n    @Test\n    public void testMockAllExcept_single() throws Exception {\n        tested = createPartialMockForAllMethodsExcept(MockSelfDemo.class, \"aMethod\");\n        tested.aMethod2();\n        expectLastCall().times(1);\n\n        final String expected = \"Hello altered world\";\n        expect(tested.getString(\"world\")).andReturn(expected);\n\n        replay(tested);\n\n        String actual = tested.aMethod();\n\n        verify(tested);\n\n        assertEquals(\"Result ought to be \\\"Hello altered world\\\".\", expected, actual);\n    }\n\n    @Test\n    public void testMockAllExcept_multiple() throws Exception {\n        tested = createPartialMockForAllMethodsExcept(MockSelfDemo.class, \"timesTwo\", \"timesThree\");\n\n        final String expected = \"A new value\";\n        expect(tested.getString2()).andReturn(expected);\n\n        replay(tested);\n\n        assertEquals(4, tested.timesTwo(2));\n        assertEquals(4, tested.timesTwo(new Integer(2)));\n        assertEquals(6, tested.timesThree(2));\n        assertEquals(expected, tested.getString2());\n\n        verify(tested);\n    }\n\n    @Test\n    public void testCreatePartialMockAndInvokeObjectConstructor() throws Exception {\n        tested = createPartialMock(MockSelfDemo.class, new String[] { \"aMethod2\", \"getString\" }, new Object());\n\n        tested.aMethod2();\n        expectLastCall().times(1);\n\n        final String expected = \"Hello altered world\";\n        expect(tested.getString(\"world\")).andReturn(expected);\n\n        replay(tested);\n\n        String actual = tested.aMethod();\n\n        verify(tested);\n\n        assertEquals(\"Result ought to be \\\"Hello altered world\\\".\", expected, actual);\n    }\n\n    @Test\n    public void testCreatePartialMockAndInvokeDefaultConstructor() throws Exception {\n        tested = createPartialMockAndInvokeDefaultConstructor(MockSelfDemo.class, \"aMethod2\", \"getString\");\n\n        tested.aMethod2();\n        expectLastCall().times(1);\n\n        final String expected = \"Hello altered world\";\n        expect(tested.getString(\"world\")).andReturn(expected);\n\n        replay(tested);\n\n        String actual = tested.aMethod();\n\n        verify(tested);\n\n        assertEquals(\"Result ought to be \\\"Hello altered world\\\".\", expected, actual);\n    }\n\n    @Test\n    public void partialMockingWithNullArgumentWorks() throws Exception {\n        final MockSelfDemo tested = createPartialMock(MockSelfDemo.class, \"establishConnection\");\n        Connection conn=null;\n        Whitebox.invokeMethod(tested, \"establishConnection\", conn);\n    }\n\n    @PrepareForTest(MockSelfWithNoDefaultConstructorDemo.class)\n    @Test\n    public void testCreatePartialMockAndInvokeDefaultConstructor_noDefaultConstructorFound() throws Exception {\n        try {\n            createPartialMockAndInvokeDefaultConstructor(MockSelfWithNoDefaultConstructorDemo.class, \"aMethod2\");\n            fail(\"Should throw ConstructorNotFoundException!\");\n        } catch (ConstructorNotFoundException e) {\n            assertEquals(\"Failed to lookup constructor with parameter types [ <none> ] in class samples.partialmocking.MockSelfWithNoDefaultConstructorDemo.\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoWithSubClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.partialmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.partialmocking.MockSelfDemoWithSubClass;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(MockSelfDemoWithSubClass.class)\npublic class MockSelfDemoWithSubClassTest {\n\n\t@Test\n\tpublic void testMockPartialMethodInChildClass() throws Exception {\n\t\tMockSelfDemoWithSubClass tested = createPartialMock(\n\t\t\t\tMockSelfDemoWithSubClass.class, \"getAMessage\",\n\t\t\t\t\"getInternalMessage\");\n\n\t\tfinal String getAMessageMock = \"Hello \";\n\t\tfinal String getInternalMessageMock = \"World!\";\n\t\tfinal String expected = getInternalMessageMock + getAMessageMock;\n\n\t\texpect(tested.getAMessage()).andReturn(getAMessageMock);\n\t\texpectPrivate(tested, \"getInternalMessage\").andReturn(\n\t\t\t\tgetInternalMessageMock);\n\n\t\treplay(tested);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(tested);\n\n\t\tassertEquals(expected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.partialmocking;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport samples.partialmocking.PartialMockingWithConstructor;\n\nimport static org.powermock.api.easymock.PowerMock.*;\n\npublic class PartialMockingWithConstructorTest {\n\n\t@Ignore(\"The initialize method is never invoked but is caught by the proxy. This is a possibly a bug in EasyMock class extensions?\")\n\t@Test\n\tpublic void testPartialMock() throws Exception {\n\n\t\t/*\n\t\t * In the original test case PartialMockingWithConstructor had\n\t\t * constructor arguments which I removed to slim down the test case,\n\t\t * originally I was using the following method to create a partial mock.\n\t\t * Regardless the same problem still occurs.\n\t\t */\n\t\tPartialMockingWithConstructor nationPartialMock = createPartialMockAndInvokeDefaultConstructor(PartialMockingWithConstructor.class, \"touch\");\n\n\t\t/*\n\t\t * The following method also causes the same problem.\n\t\t */\n\n\t\t// Nation nationPartialMock =\n\t\t// createPartialMockAndInvokeDefaultConstructor(Nation.class,\"touch\");\n\t\treplay(nationPartialMock);\n\n\t\t// Uncommenting the following line has no effect on the test result.\n\t\t// nationPartialMock.initialize();\n\n\t\tverify(nationPartialMock);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorUsingEasyMockTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.partialmocking;\n\nimport org.easymock.ConstructorArgs;\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport samples.partialmocking.PartialMockingWithConstructor;\n\nimport java.lang.reflect.Method;\n\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.powermock.api.easymock.PowerMock.createMock;\n\npublic class PartialMockingWithConstructorUsingEasyMockTest {\n\n\t@SuppressWarnings(\"deprecation\")\n    @Ignore(\"The initialize method is never invoked but is caught by the proxy. This is a possibly a bug in EasyMock class extensions?\")\n\t@Test\n\tpublic void testPartialMock() throws Exception {\n\n\t\t/*\n\t\t * In the original test case PartialMockingWithConstructor had\n\t\t * constructor arguments which I removed to slim down the test case,\n\t\t * originally I was using the following method to create a partial mock.\n\t\t * Regardless the same problem still occurs.\n\t\t */\n\t\tConstructorArgs args = new ConstructorArgs(PartialMockingWithConstructor.class.getConstructor());\n\t\tMethod touchMethod = PartialMockingWithConstructor.class.getMethod(\"touch\");\n\n\t\tPartialMockingWithConstructor nationPartialMock = createMock(PartialMockingWithConstructor.class, args, touchMethod);\n\n\t\t/*\n\t\t * The following method also causes the same problem.\n\t\t */\n\n\t\t// Nation nationPartialMock =\n\t\t// createPartialMockAndInvokeDefaultConstructor(Nation.class,\"touch\");\n\t\treplay(nationPartialMock);\n\n\t\t// Uncommenting the following line has no effect on the test result.\n\t\t// nationPartialMock.initialize();\n\n\t\tverify(nationPartialMock);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/powermockignore/PowerMockIgnoreAndPrepareForTest.java",
    "content": "package samples.junit4.powermockignore;\n\nimport net.bytebuddy.utility.RandomString;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PowerMockIgnore;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.StaticService;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PowerMockIgnore(\"samples.*\")\n@PrepareForTest(StaticService.class)\npublic class PowerMockIgnoreAndPrepareForTest {\n\n    @Test public void powermock_ignore_annotation_and_prepare_for_test_annotation_can_be_combined() {\n        mockStatic(StaticService.class);\n        \n        final String expected = RandomString.make(5);\n        \n        expect(StaticService.doStatic(5)).andReturn(expected);\n        replay(StaticService.class);\n\n        assertThat(StaticService.doStatic(5))\n            .isEqualTo(expected);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/prepareeverything/ExpectNewDemoUsingThePrepareEverythingAnnotationTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.prepareeverything;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareEverythingForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport samples.Service;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.expectnew.ExpectNewServiceUser;\nimport samples.expectnew.VarArgsConstructorDemo;\nimport samples.newmocking.MyClass;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static org.easymock.EasyMock.*;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.junit.Assert.*;\nimport static org.powermock.api.easymock.PowerMock.createMock;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate new instance mocking using expectNew(..) with the\n * {@link PrepareEverythingForTest} annotation and replayAll and verifyAll.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareEverythingForTest\npublic class ExpectNewDemoUsingThePrepareEverythingAnnotationTest {\n\n    @Test\n    public void testNewWithCheckedException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing checked exception\";\n        expectNew(MyClass.class).andThrow(new IOException(expectedFailMessage));\n\n        replayAll();\n\n        try {\n            tested.throwExceptionAndWrapInRunTimeWhenInvoction();\n            fail(\"Should throw a checked Exception!\");\n        } catch (RuntimeException e) {\n            assertTrue(e.getCause() instanceof IOException);\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verifyAll();\n    }\n\n    @PrepareEverythingForTest\n    @Test\n    public void testGetMessage() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        expect(myClassMock.getMessage()).andReturn(\"Hello altered World\");\n\n        replayAll();\n\n        String actual = tested.getMessage();\n\n        verifyAll();\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testGetMessageWithArgument() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = createMock(MyClass.class);\n        expectNew(MyClass.class).andReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        expect(myClassMock.getMessage(\"test\")).andReturn(\"Hello altered World\");\n        replayAll();\n\n        String actual = tested.getMessageWithArgument();\n\n        verifyAll();\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testInvokeVoidMethod() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = createMock(MyClass.class);\n        expectNew(MyClass.class).andReturn(myClassMock);\n\n        myClassMock.voidMethod();\n        expectLastCall().times(1);\n\n        replayAll();\n\n        tested.invokeVoidMethod();\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithRuntimeException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing\";\n        expectNew(MyClass.class).andThrow(new RuntimeException(expectedFailMessage));\n\n        replayAll();\n\n        try {\n            tested.throwExceptionWhenInvoction();\n            fail(\"Should throw RuntimeException!\");\n        } catch (RuntimeException e) {\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verifyAll();\n    }\n\n    @Test\n    public void testPreviousProblemsWithByteCodeManipulation() throws Exception {\n        MyClass myClassMock1 = createMock(MyClass.class);\n        expect(myClassMock1.getMessage()).andReturn(\"Hello\");\n        expect(myClassMock1.getMessage()).andReturn(\"World\");\n        replayAll();\n        assertEquals(\"Hello\", myClassMock1.getMessage());\n        assertEquals(\"World\", myClassMock1.getMessage());\n        verifyAll();\n    }\n\n    @Test\n    public void testMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n        MyClass myClassMock2 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1);\n        expectNew(MyClass.class).andReturn(myClassMock2);\n\n        expect(myClassMock1.getMessage()).andReturn(\"Hello \");\n        expect(myClassMock2.getMessage()).andReturn(\"World\");\n\n        replayAll();\n\n        final String actual = tested.multipleNew();\n\n        verifyAll();\n\n        assertEquals(\"Hello World\", actual);\n    }\n\n    @Test\n    public void testSimpleMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(3);\n\n        replayAll();\n\n        tested.simpleMultipleNew();\n\n        verifyAll();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(4);\n\n        replayAll();\n\n        tested.simpleMultipleNew();\n\n        try {\n            verifyAll();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Expectation failure on verify:\" + \"\\n    samples.newmocking.MyClass(): expected: 4, actual: 3\", e\n                    .getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(2);\n\n        replayAll();\n        try {\n            tested.simpleMultipleNew();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected constructor call samples.newmocking.MyClass():\"\n                    + \"\\n    samples.newmocking.MyClass(): expected: 2, actual: 3\", e.getMessage());\n        }\n    }\n\n    /**\n     * Verifies that the issue\n     * http://code.google.com/p/powermock/issues/detail?id=10 is solved.\n     */\n    @Test\n    public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(2);\n\n        replayAll();\n        try {\n            Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected constructor call samples.newmocking.MyClass():\"\n                    + \"\\n    samples.newmocking.MyClass(): expected: 2, actual: 3\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_ok() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(3);\n\n        replayAll();\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n    }\n\n    @Test\n    public void testSimpleSingleNew_withOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).once();\n\n        replayAll();\n        tested.simpleSingleNew();\n        verifyAll();\n    }\n\n    @Test\n    public void testSimpleSingleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce();\n\n        replayAll();\n        tested.simpleSingleNew();\n        verifyAll();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce();\n\n        replayAll();\n        tested.simpleMultipleNew();\n        verifyAll();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_lowerBoundLessThan0() throws Exception {\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        try {\n\n            expectNew(MyClass.class).andReturn(myClassMock1).times(-20, 2);\n            fail(\"Should throw IllegalArgumentException.\");\n        } catch (IllegalArgumentException e) {\n            assertEquals(\"minimum must be >= 0\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_upperBoundLessThan0() throws Exception {\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n        try {\n            expectNew(MyClass.class).andReturn(myClassMock1).times(-1, -2);\n            fail(\"Should throw IllegalArgumentException.\");\n        } catch (IllegalArgumentException e) {\n            assertTrue(e.getMessage().contains(\"<=\"));\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_upperBoundLessThanLowerBound() throws Exception {\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n        try {\n            expectNew(MyClass.class).andReturn(myClassMock1).times(10, 2);\n            fail(\"Should throw IllegalArgumentException.\");\n        } catch (IllegalArgumentException e) {\n            assertTrue(e.getMessage().contains(\"<=\"));\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_OK() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(1, 5);\n\n        replayAll();\n\n        tested.simpleMultipleNew();\n\n        verifyAll();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_anyTimes() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).anyTimes();\n\n        replayAll();\n\n        tested.simpleMultipleNew();\n\n        verifyAll();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withRange_notWithinRange() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(5, 7);\n\n        replayAll();\n\n        tested.simpleMultipleNew();\n\n        try {\n            verifyAll();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Expectation failure on verify:\" + \"\\n    samples.newmocking.MyClass(): expected: between 5 and 7, actual: 3\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void testAlternativeFlow() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        expectNew(DataInputStream.class, new Object[] { null }).andThrow(new RuntimeException(\"error\"));\n\n        replayAll();\n\n        InputStream stream = tested.alternativePath();\n\n        verifyAll();\n\n        assertNotNull(\"The returned inputstream should not be null.\", stream);\n        assertTrue(\"The returned inputstream should be an instance of ByteArrayInputStream.\", stream instanceof ByteArrayInputStream);\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).times(4);\n\n        replayAll();\n        try {\n            Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n            verifyAll();\n            fail(\"Should throw an exception!.\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Expectation failure on verify:\" + \"\\n    samples.newmocking.MyClass(): expected: 4, actual: 3\", e\n                    .getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class);\n        Service serviceMock = createMock(Service.class);\n\n        expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock);\n        expect(expectNewServiceImplMock.useService()).andReturn(expected);\n\n        replayAll();\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithVarArgs() throws Exception {\n        final String firstString = \"hello\";\n        final String secondString = \"world\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        expectNew(VarArgsConstructorDemo.class, firstString, secondString).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getAllMessages()).andReturn(new String[] { firstString, secondString });\n\n        replayAll();\n\n        String[] varArgs = tested.newVarArgs(firstString, secondString);\n        assertEquals(2, varArgs.length);\n        assertEquals(firstString, varArgs[0]);\n        assertEquals(secondString, varArgs[1]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception {\n        final Object object = new Object();\n        try {\n            expectNew(VarArgsConstructorDemo.class, object);\n            fail(\"Should throw ConstructorNotFoundException!\");\n        } catch (ConstructorNotFoundException e) {\n            assertEquals(\"No constructor found in class '\" + VarArgsConstructorDemo.class.getName() + \"' with parameter types: [ \"\n                    + object.getClass().getName() + \" ].\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        Service serviceMock = createMock(Service.class);\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final Service serviceSubTypeInstance = new Service() {\n\n            @Override\n            public String getServiceMessage() {\n                return \"message\";\n            }\n        };\n\n        expectNew(VarArgsConstructorDemo.class, serviceSubTypeInstance, serviceMock).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getAllServices()).andReturn(new Service[] { serviceMock });\n\n        replayAll();\n\n        Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock);\n        assertEquals(1, varArgs.length);\n        assertSame(serviceMock, varArgs[0]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithArrayVarArgs() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[] { 42 };\n        final byte[] byteArrayTwo = new byte[] { 17 };\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne });\n\n        replayAll();\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsAndMatchers() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[] { 42 };\n        final byte[] byteArrayTwo = new byte[] { 17 };\n        expectNew(VarArgsConstructorDemo.class, aryEq(byteArrayOne), aryEq(byteArrayTwo)).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne });\n\n        replayAll();\n\n        byte[][] varArgs = tested.newVarArgsWithMatchers();\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[] { 17 };\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo });\n\n        replayAll();\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[] { 42 };\n        final byte[] byteArrayTwo = null;\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne });\n\n        replayAll();\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[] { 42 };\n        final byte[] byteArrayThree = null;\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo, byteArrayThree).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo });\n\n        replayAll();\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = null;\n        expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock);\n        expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo });\n\n        replayAll();\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyAll();\n    }\n\n    @Test\n    public void testNewWithWrongArgument() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class);\n        Service serviceMock = createMock(Service.class);\n\n        expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock);\n        expect(expectNewServiceImplMock.useService()).andReturn(expected);\n\n        replayAll();\n\n        try {\n            assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes));\n            verifyAll();\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\n                    \"\\n  Unexpected constructor call samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 4 (int)):\"\n                            + \"\\n    samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 2 (int)): expected: 1, actual: 0\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void testExpectNewButNoNewCallWasMade() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = createMock(MyClass.class);\n\n        expectNew(MyClass.class).andReturn(myClassMock1).once();\n\n        replayAll();\n        try {\n            tested.makeDate();\n            verifyAll();\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertTrue(e.getMessage().contains(MyClass.class.getName() + \"(): expected: 1, actual: 0\"));\n        }\n    }\n}"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/privateandfinal/PrivateFinalTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.privateandfinal;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.privateandfinal.PrivateFinal;\n\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.createPartialMock;\nimport static org.powermock.api.easymock.PowerMock.expectPrivate;\n\n\n/**\n * Test class to demonstrate private+final method mocking.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PrivateFinal.class)\npublic class PrivateFinalTest {\n\n\t@Test\n\tpublic void testMockPrivatAndFinal() throws Exception {\n\n\t\tPrivateFinal tested = createPartialMock(PrivateFinal.class,\n\t\t\t\t\"sayIt\");\n\t\tString expected = \"Hello altered World\";\n\t\texpectPrivate(tested, \"sayIt\", \"name\").andReturn(expected);\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"name\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMultiplePartialMocksOfSameType() throws Exception {\n\t\tPrivateFinal tested1 = createPartialMock(PrivateFinal.class,\n\t\t\t\t\"sayIt\");\n\t\tString expected1 = \"Hello altered World\";\n\t\texpectPrivate(tested1, \"sayIt\", \"name\").andReturn(expected1);\n\t\treplay(tested1);\n\t\tPrivateFinal tested2 = createPartialMock(PrivateFinal.class,\n\t\t\t\t\"sayIt\");\n\t\tString expected2 = \"Hello qweqweqwe\";\n\t\texpectPrivate(tested2, \"sayIt\", \"name\").andReturn(expected2);\n\t\treplay(tested2);\n\n\t\tString actual1 = tested1.say(\"name\");\n\t\tverify(tested1);\n\t\tassertEquals(\"Expected and actual did not match\", expected1, actual1);\n\t\tString actual2 = tested2.say(\"name\");\n\t\tverify(tested2);\n\t\tassertEquals(\"Expected and actual did not match\", expected2, actual2);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/privatefield/MockSelfPrivateFieldServiceClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.privatefield;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.Service;\nimport samples.privatefield.MockSelfPrivateFieldServiceClass;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\nimport static org.powermock.reflect.Whitebox.setInternalState;\n\n/**\n * A test class that demonstrate how to test classes that uses a private field\n * for a service and has no corresponding setter and at the same time mocking a\n * method of the actual test class. This is approach is common in DI frameworks\n * like Guice and Wicket IoC.\n * \n * @author Johan Haleby\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(MockSelfPrivateFieldServiceClass.class)\npublic class MockSelfPrivateFieldServiceClassTest {\n\n\t@Test\n\tpublic void testGetCompositeMessage() throws Exception {\n\t\tMockSelfPrivateFieldServiceClass tested = createPartialMock(MockSelfPrivateFieldServiceClass.class, \"getOwnMessage\");\n\n\t\tService serviceMock = createMock(Service.class);\n\t\tsetInternalState(tested, \"service\", serviceMock, MockSelfPrivateFieldServiceClass.class);\n\n\t\tfinal String expected = \"Hello world\";\n\t\texpectPrivate(tested, \"getOwnMessage\").andReturn(\"Hello\");\n\t\texpect(serviceMock.getServiceMessage()).andReturn(\" world\");\n\n\t\treplay(serviceMock);\n\t\treplay(tested);\n\n\t\tfinal String actual = tested.getCompositeMessage();\n\n\t\tverify(serviceMock);\n\t\tverify(tested);\n\n\t\tassertEquals(expected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/privatefield/SimplePrivateFieldServiceClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.privatefield;\n\nimport org.junit.Test;\nimport samples.Service;\nimport samples.privatefield.SimplePrivateFieldServiceClass;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\nimport static org.powermock.reflect.Whitebox.setInternalState;\n\n/**\n * A test class that demonstrate how to test class that uses a private field for\n * a Service and has no corresponding setter. This is approach is common in DI\n * frameworks like Guice and Wicket IoC.\n * \n * @author Johan Haleby\n */\npublic class SimplePrivateFieldServiceClassTest {\n\n\t@Test\n\tpublic void testSimplePrivateFieldServiceClass() throws Exception {\n\t\tSimplePrivateFieldServiceClass tested = new SimplePrivateFieldServiceClass();\n\t\tService serviceMock = createMock(Service.class);\n\t\tsetInternalState(tested, \"service\", serviceMock, SimplePrivateFieldServiceClass.class);\n\n\t\tfinal String expected = \"Hello world!\";\n\t\texpect(serviceMock.getServiceMessage()).andReturn(expected);\n\n\t\treplay(serviceMock);\n\t\tfinal String actual = tested.useService();\n\n\t\tverify(serviceMock);\n\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void testSimplePrivateFieldServiceClassTypeSafe() throws Exception {\n\t\tSimplePrivateFieldServiceClass tested = new SimplePrivateFieldServiceClass();\n\t\tService serviceMock = createMock(Service.class);\n\t\tsetInternalState(tested, serviceMock);\n\n\t\tfinal String expected = \"Hello world!\";\n\t\texpect(serviceMock.getServiceMessage()).andReturn(expected);\n\n\t\treplay(serviceMock);\n\t\tfinal String actual = tested.useService();\n\n\t\tverify(serviceMock);\n\n\t\tassertEquals(expected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/privatemocking/PrivateMethodDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.privatemocking;\n\nimport org.easymock.EasyMock;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.privatemocking.PrivateMethodDemo;\n\nimport java.lang.reflect.Method;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate private method mocking.\n * \n * @author Johan Haleby\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PrivateMethodDemo.class)\npublic class PrivateMethodDemoTest {\n\n\t@Test\n\tpublic void testMockPrivateMethod() throws Exception {\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"sayIt\", String.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpectPrivate(tested, \"sayIt\", \"name\").andReturn(expected);\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"name\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMockPrivateMethod_withArgument() throws Exception {\n\t\tPrivateMethodDemo tested = new PrivateMethodDemo();\n\t\tString expected = \"Hello altered World\";\n\n\t\tString actual = Whitebox.invokeMethod(tested, \"sayIt\",\n\t\t\t\t\"altered World\");\n\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testInvokePrivateMethod() throws Exception {\n\n\t\tPrivateMethodDemo tested = new PrivateMethodDemo();\n\t\tString expected = \"Hello world\";\n\n\t\tString actual = Whitebox.invokeMethod(tested, \"sayIt\");\n\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMethodCallingPrimitiveTestMethod() throws Exception {\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"aTestMethod\", int.class);\n\n\t\tfinal int expected = 42;\n\t\texpectPrivate(tested, \"aTestMethod\", new Class<?>[] { int.class }, 10)\n\t\t\t\t.andReturn(expected);\n\n\t\treplay(tested);\n\n\t\tfinal int actual = tested.methodCallingPrimitiveTestMethod();\n\n\t\tverify(tested);\n\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMethodCallingWrappedTestMethod() throws Exception {\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"aTestMethod\", Integer.class);\n\n\t\tfinal int expected = 42;\n\t\texpectPrivate(tested, \"aTestMethod\", new Class<?>[] { Integer.class },\n\t\t\t\tnew Integer(15)).andReturn(expected);\n\n\t\treplay(tested);\n\n\t\tfinal int actual = tested.methodCallingWrappedTestMethod();\n\n\t\tverify(tested);\n\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMethodCallingWrappedTestMethod_reflectiveMethodLookup()\n\t\t\tthrows Exception {\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"aTestMethod\", Integer.class);\n\n\t\tfinal Method methodToExpect = PrivateMethodDemo.class\n\t\t\t\t.getDeclaredMethod(\"aTestMethod\", Integer.class);\n\n\t\tfinal int expected = 42;\n\t\texpectPrivate(tested, methodToExpect, 15).andReturn(expected);\n\n\t\treplay(tested);\n\n\t\tfinal int actual = tested.methodCallingWrappedTestMethod();\n\n\t\tverify(tested);\n\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testExpectPrivateWithArrayMatcher() throws Exception {\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"doArrayInternal\");\n\n\t\texpectPrivate(tested, \"doArrayInternal\", EasyMock\n\t\t\t\t.aryEq((Object[]) new String[] { \"hello\" }));\n\n\t\treplay(tested);\n\n\t\ttested.doArrayStuff(\"hello\");\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testExpectPrivateWithObjectMatcher() throws Exception {\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"doObjectInternal\");\n\n\t\texpectPrivate(tested, \"doObjectInternal\", EasyMock\n\t\t\t\t.isA(CharSequence.class));\n\n\t\treplay(tested);\n\n\t\ttested.doObjectStuff(\"hello\");\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testExpectPrivateMethodWithVarArgsParameters() throws Exception {\n\t\tfinal String methodToExpect = \"varArgsMethod\";\n\t\tfinal int expected = 7;\n\t\tfinal int valueA = 2;\n\t\tfinal int valueB = 3;\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\tmethodToExpect);\n\n\t\texpectPrivate(tested, methodToExpect, valueA, valueB).andReturn(\n\t\t\t\texpected);\n\n\t\treplay(tested);\n\n\t\tassertEquals(expected, tested.invokeVarArgsMethod(valueA, valueB));\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testExpectPrivateMethodWithoutSpecifyingMethodName_firstArgumentIsOfStringType()\n\t\t\tthrows Exception {\n\t\tfinal String expected = \"Hello world\";\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"sayIt\");\n\n\t\texpectPrivate(tested, (String) null, \"firstName\", \" \", \"lastName\")\n\t\t\t\t.andReturn(expected);\n\n\t\treplay(tested);\n\n\t\tassertEquals(expected, tested.enhancedSay(\"firstName\", \"lastName\"));\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testExpectPrivateMethodWithoutSpecifyingMethodName()\n\t\t\tthrows Exception {\n\t\tfinal String expected = \"Hello world\";\n\t\tPrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,\n\t\t\t\t\"doSayYear\");\n\n\t\texpectPrivate(tested, 22, \"name\").andReturn(expected);\n\n\t\treplay(tested);\n\n\t\tassertEquals(expected, tested.sayYear(\"name\", 22));\n\n\t\tverify(tested);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/reflection/ReflectionInstantiatorTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.reflection;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.reflection.ReflectionInstantiator;\nimport samples.reflection.UseMe;\n\nimport static org.junit.Assert.assertTrue;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { UseMe.class })\npublic class ReflectionInstantiatorTest {\n\n\t@Test\n\tpublic void whenClassIsInstantiatedUsingReflectionMakeSureItCanBeCastedToPowerMockLoadedVersionOfTheClass()\n\t\t\tthrows Exception {\n\t\tReflectionInstantiator reflectionInstantiator = new ReflectionInstantiator();\n\t\tassertTrue(\n\t\t\t\t\"Reflection instantiation doesn't work, Thread context class-loader not set to MockCL\",\n\t\t\t\treflectionInstantiator.instantiateUseMe());\n\t}\n\n\t@Test\n\t@PrepareForTest(UseMe.class)\n\tpublic void whenClassIsInstantiatedUsingReflectionMakeSureItCanBeCastedToPowerMockLoadedVersionOfTheClassWhenUsingChunking()\n\t\t\tthrows Exception {\n\t\tReflectionInstantiator reflectionInstantiator = new ReflectionInstantiator();\n\t\tassertTrue(\n\t\t\t\t\"Reflection instantiation doesn't work, Thread context class-loader not set to MockCL\",\n\t\t\t\treflectionInstantiator.instantiateUseMe());\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForExpectNewTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.replayall;\n\nimport org.easymock.EasyMock;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.Service;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.expectnew.ExpectNewServiceUser;\nimport samples.newmocking.MyClass;\n\nimport java.io.IOException;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.*;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * The purpose of this test is to try-out the replay all functionality in\n * PowerMock in combination with expectNew.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MyClass.class, ExpectNewDemo.class })\npublic class ReplayAllForExpectNewTest {\n\n\t@Test\n\tpublic void testNewWithCheckedException() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\n\t\tfinal String expectedFailMessage = \"testing checked exception\";\n\t\texpectNew(MyClass.class).andThrow(new IOException(expectedFailMessage));\n\n\t\treplayAll();\n\n\t\ttry {\n\t\t\ttested.throwExceptionAndWrapInRunTimeWhenInvoction();\n\t\t\tfail(\"Should throw a checked Exception!\");\n\t\t} catch (RuntimeException e) {\n\t\t\tassertTrue(e.getCause() instanceof IOException);\n\t\t\tassertEquals(expectedFailMessage, e.getMessage());\n\t\t}\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void testGetMessage() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\t\tMyClass myClassMock = createMock(MyClass.class);\n\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\n\t\tString expected = \"Hello altered World\";\n\t\texpect(myClassMock.getMessage()).andReturn(\"Hello altered World\");\n\n\t\treplayAll();\n\n\t\tString actual = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testReplayAllWithExpectNewWhenTheClassBeingConstructedIsNotPreparedForTest() throws Exception {\n\t\tfinal int numberOfTimes = 2;\n\t\tfinal String expected = \"used\";\n\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\t\tExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class);\n\t\tService serviceMock = createMock(Service.class);\n\n\t\texpectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock);\n\t\texpect(expectNewServiceImplMock.useService()).andReturn(expected);\n\n\t\treplayAll();\n\n\t\tassertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n\t\tverifyAll();\n\t}\n\n\t@Test\n\tpublic void testReplayAllWithAdditionalMocks() throws Exception {\n\t\tfinal int numberOfTimes = 2;\n\t\tfinal String expected = \"used\";\n\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\t\tExpectNewServiceUser expectNewServiceImplMock = EasyMock.createMock(ExpectNewServiceUser.class);\n\t\tService serviceMock = createMock(Service.class);\n\n\t\texpectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock);\n\t\texpect(expectNewServiceImplMock.useService()).andReturn(expected);\n\n\t\treplayAll(expectNewServiceImplMock);\n\n\t\tassertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n\t\tverifyAll();\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForStaticMethodsTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.replayall;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticandinstance.StaticAndInstanceDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * The purpose of this test is to try-out the replay all functionality in\n * PowerMock in combination with static and instance mocking.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class ReplayAllForStaticMethodsTest {\n\n\t@Test\n\tpublic void testMockStaticMethodAndInstanceMethod() throws Exception {\n\t\tmockStaticPartial(StaticAndInstanceDemo.class, \"getStaticMessage\");\n\n\t\tStaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, \"getPrivateMessage\");\n\n\t\tfinal String staticExpected = \"a static message\";\n\t\texpect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected);\n\t\tfinal String privateExpected = \"A private message \";\n\t\texpectPrivate(tested, \"getPrivateMessage\").andReturn(privateExpected);\n\n\t\treplayAll();\n\n\t\tString actual = tested.getMessage();\n\n\t\tverifyAll();\n\n\t\tassertEquals(privateExpected + staticExpected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetForStaticMethodsTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.resetmock;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.StaticService;\n\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Asserts that it works to reset mocks for static methods even after verify has\n * been invoked.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticService.class)\npublic class ResetForStaticMethodsTest {\n\n\t@Test\n\tpublic void assertThatResetWorksForStaticMethods() throws InterruptedException {\n\t\tmockStatic(StaticService.class);\n\n\t\tStaticService.sayHello();\n\t\texpectLastCall().once();\n\n\t\treplay(StaticService.class);\n\n\t\tStaticService.sayHello();\n\n\t\tverify(StaticService.class);\n\n\t\treset(StaticService.class);\n\n\t\tStaticService.sayHello();\n\t\texpectLastCall().once();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetMockTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit4.resetmock;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Tests to verify that the reset functionality works.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ExpectNewDemo.class)\npublic class ResetMockTest {\n\n\t@Test\n\tpublic void assertManualResetWorks() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\n\t\tMyClass myClassMock = createMock(MyClass.class);\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\t\texpect(myClassMock.getMessage()).andReturn(\"message\");\n\n\t\treplayAll();\n\n\t\tString message = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"message\", message);\n\n\t\treset(myClassMock);\n\t\treset(MyClass.class);\n\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\t\texpect(myClassMock.getMessage()).andReturn(\"message\");\n\n\t\treplayAll();\n\n\t\tmessage = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"message\", message);\n\t}\n\n\t@Test\n\tpublic void assertManualResetWorksWhenMixingInstanceAndClassMocks() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\n\t\tMyClass myClassMock = createMock(MyClass.class);\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\t\texpect(myClassMock.getMessage()).andReturn(\"message\");\n\n\t\treplayAll();\n\n\t\tString message = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"message\", message);\n\n\t\treset(myClassMock, MyClass.class);\n\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\t\texpect(myClassMock.getMessage()).andReturn(\"message\");\n\n\t\treplayAll();\n\n\t\tmessage = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"message\", message);\n\t}\n\n\t@Test\n\tpublic void assertResetAllWorks() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\n\t\tMyClass myClassMock = createMock(MyClass.class);\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\t\texpect(myClassMock.getMessage()).andReturn(\"message\");\n\n\t\treplayAll();\n\n\t\tString message = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"message\", message);\n\n\t\tresetAll();\n\n\t\texpectNew(MyClass.class).andReturn(myClassMock);\n\t\texpect(myClassMock.getMessage()).andReturn(\"message\");\n\n\t\treplayAll();\n\n\t\tmessage = tested.getMessage();\n\n\t\tverifyAll();\n\t\tassertEquals(\"message\", message);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/servletmocking/SampleServletTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit4.servletmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.servletmocking.SampleServlet;\n\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.PrintWriter;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SampleServlet.class)\npublic class SampleServletTest {\n\n    @Test\n    public void doGet() throws Exception {\n        SampleServlet servlet = new SampleServlet();\n\n        HttpServletResponse response = createMock(HttpServletResponse.class);\n        PrintWriter writer = createMock(PrintWriter.class);\n\n        expect(response.getWriter()).andReturn(writer);\n        writer.write(\"out\");\n\n        replay(response, writer);\n\n        servlet.doGet(null, response);\n\n        verify(response, writer);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/simplereturn/SimpleReturnExampleUserTest.java",
    "content": "package samples.junit4.simplereturn;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.simplereturn.SimpleReturnExample;\nimport samples.simplereturn.SimpleReturnExampleUser;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SimpleReturnExample.class)\npublic class SimpleReturnExampleUserTest {\n\n\t@Test\n\tpublic void testCreateMockDelegatedToEasyMock() throws Exception {\n\t\tSimpleReturnExample mock = createMock(SimpleReturnExample.class);\n\t\texpect(mock.mySimpleMethod()).andReturn(2);\n\n\t\treplay(mock);\n\n\t\tassertEquals(2, new SimpleReturnExampleUser(mock).myMethod());\n\n\t\tverify(mock);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/singleton/LogicAndTestInSameClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit4.singleton;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * A simple test that asserts that it's possible execute a test from the same\n * class that defines the logic to test.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticService.class, LogicAndTestInSameClassTest.class })\npublic class LogicAndTestInSameClassTest {\n\n\tprivate static String invokeMethod() {\n\t\treturn StaticService.say(\"hello\");\n\t}\n\n\t@Test\n\tpublic void assertThatTestAndInstanceCanBeInSameClass() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplayAll();\n\t\tassertEquals(expected, LogicAndTestInSameClassTest.invokeMethod());\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/singleton/MockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.singleton;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n * \n * @author Johan Haleby\n * @author Jan Kronquist\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticService.class, StaticHelper.class })\npublic class MockStaticTest {\n\n\t@Test\n\tpublic void testMockStatic() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.say(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Singleton still be mocked by now.\n\t\ttry {\n\t\t\tStaticService.say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call StaticService.say(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testMockStaticFinal() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayFinal(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayFinal(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Singleton still be mocked by now.\n\t\ttry {\n\t\t\tStaticService.sayFinal(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call StaticService.sayFinal(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testMockStaticNative() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayNative(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMockStaticFinalNative() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayFinalNative(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void mockAStaticMethod() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"qwe\";\n\t\texpect(StaticService.doStatic(5)).andReturn(expected);\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.doStatic(5);\n\t\tassertEquals(expected, actual);\n\t\tverify(StaticService.class);\n\t}\n\n\t@Test\n\tpublic void mockMockStatic_times2() throws Exception {\n\t\tmockStatic(StaticHelper.class);\n\t\tStaticHelper.sayHelloHelper();\n\t\texpectLastCall().times(2);\n\t\treplay(StaticHelper.class);\n\n\t\tStaticService.sayHello();\n\n\t\tverify(StaticHelper.class);\n\t}\n\n\t@Test\n\tpublic void mockStaticCallingOtherStatic() throws Exception {\n\t\tmockStatic(StaticHelper.class);\n\t\tStaticHelper.sayHelloAgain();\n\t\texpectLastCall().times(2);\n\t\treplay(StaticHelper.class);\n\n\t\tStaticService.sayHelloAgain();\n\n\t\tverify(StaticHelper.class);\n\t}\n\n\t@Test\n\tpublic void testMockPrivateStatic() throws Exception {\n\t\tmockStaticPartial(StaticService.class, \"sayPrivateStatic\", String.class);\n\n\t\tfinal String expected = \"Hello world\";\n\t\texpectPrivate(StaticService.class, \"sayPrivateStatic\", \"name\").andReturn(expected);\n\n\t\treplay(StaticService.class);\n\n\t\tString actual = Whitebox.invokeMethod(StaticService.class, \"sayPrivateStatic\", \"name\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMockPrivateFinalStatic() throws Exception {\n\t\tmockStaticPartial(StaticService.class, \"sayPrivateFinalStatic\", String.class);\n\n\t\tfinal String expected = \"Hello world\";\n\t\texpectPrivate(StaticService.class, \"sayPrivateFinalStatic\", \"name\").andReturn(expected);\n\n\t\treplay(StaticService.class);\n\n\t\tString actual = Whitebox.invokeMethod(StaticService.class, \"sayPrivateFinalStatic\", \"name\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void testMockPrivateNativeFinalStatic() throws Exception {\n\t\tmockStaticPartial(StaticService.class, \"sayPrivateNativeFinalStatic\", String.class);\n\n\t\tfinal String expected = \"Hello world\";\n\t\texpectPrivate(StaticService.class, \"sayPrivateNativeFinalStatic\", \"name\").andReturn(expected);\n\n\t\treplay(StaticService.class);\n\n\t\tString actual = Whitebox.invokeMethod(StaticService.class, \"sayPrivateNativeFinalStatic\", \"name\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void innerClassesWork() {\n\t\tassertEquals(17, StaticService.getNumberFromInner());\n\t}\n\n\t@Test\n\tpublic void innerInstanceClassesWork() {\n\t\tassertEquals(23, StaticService.getNumberFromInnerInstance());\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/singleton/SimpleStaticServiceTest.java",
    "content": "package samples.junit4.singleton;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.SimpleStaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SimpleStaticService.class)\npublic class SimpleStaticServiceTest {\n\n    @Test\n    public void testMockStatic() throws Exception {\n        mockStatic(SimpleStaticService.class);\n        final String expected = \"Hello altered World\";\n\n        expect(SimpleStaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n        replay(SimpleStaticService.class);\n\n        final String actual = SimpleStaticService.say(\"hello\");\n\n        verify(SimpleStaticService.class);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n\n        // Singleton still be mocked by now.\n        try {\n            SimpleStaticService.say(\"world\");\n            fail(\"Should throw AssertionError!\");\n        } catch (final AssertionError e) {\n            assertEquals(\"\\n  Unexpected method call SimpleStaticService.say(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/stackoverflow/EvilHashCode.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.stackoverflow;\n\npublic class EvilHashCode {\n    //Required to produce error\n    public String s = returnS();\n\n    public String returnS()\n    {\n            return \"s\";\n    }\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn evilHashCode();\n\t}\n\n\tpublic int evilHashCode() {\n\t\treturn 3;\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/stackoverflow/StackOverFlowTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.stackoverflow;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n/**\n * Make sure we don't get a stackOverFlowError here. Thanks to ride.sputnik for\n * reporting this!\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(EvilHashCode.class)\npublic class StackOverFlowTest {\n\n\t@Test\n\tpublic void testStackOverFlowShouldNotOccur() throws Exception {\n\t\tnew EvilHashCode();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.staticandinstance;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticandinstance.StaticAndInstanceDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class StaticAndInstanceDemoTest {\n\n\t@Test\n\tpublic void testMockStaticMethodAndInstanceMethod() throws Exception {\n\t\tmockStaticPartial(StaticAndInstanceDemo.class, \"getStaticMessage\");\n\n\t\tStaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class,\n\t\t\t\t\"getPrivateMessage\");\n\n\t\tfinal String staticExpected = \"a static message\";\n\t\texpect(StaticAndInstanceDemo.getStaticMessage()).andReturn(\n\t\t\t\tstaticExpected);\n\t\tfinal String privateExpected = \"A private message \";\n\t\texpectPrivate(tested, \"getPrivateMessage\").andReturn(privateExpected);\n\n\t\treplay(tested);\n\t\treplay(StaticAndInstanceDemo.class);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(tested);\n\t\tverify(StaticAndInstanceDemo.class);\n\n\t\tassertEquals(privateExpected + staticExpected, actual);\n\t}\n\n\t@Test\n\tpublic void testMockPrivateButNotStatic() throws Exception {\n\t\tStaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class,\n\t\t\t\t\"getPrivateMessage\");\n\n\t\tfinal String privateExpected = \"A private message \";\n\t\texpectPrivate(tested, \"getPrivateMessage\").andReturn(privateExpected);\n\n\t\treplay(tested);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(tested);\n\n\t\tassertEquals(privateExpected + \"hello world!\", actual);\n\t}\n\n\t@Test\n\tpublic void testMockStaticButNotInstance() throws Exception {\n\t\tStaticAndInstanceDemo tested = new StaticAndInstanceDemo();\n\n\t\tmockStaticPartial(StaticAndInstanceDemo.class, \"getStaticMessage\");\n\n\t\tfinal String staticExpected = \"static message\";\n\t\texpect(StaticAndInstanceDemo.getStaticMessage()).andReturn(\n\t\t\t\tstaticExpected);\n\n\t\treplay(StaticAndInstanceDemo.class);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(StaticAndInstanceDemo.class);\n\n\t\tassertEquals(\"Private \" + staticExpected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceWithConstructorCodeDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.staticandinstance;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticandinstance.StaticAndInstanceDemo;\nimport samples.staticandinstance.StaticAndInstanceWithConstructorCodeDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * The purpose of this test class is to verify that the\n * http://code.google.com/p/powermock/issues/detail?id=4 is fixed.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class StaticAndInstanceWithConstructorCodeDemoTest {\n\n\t@Test\n\tpublic void testStaticAndInstanceWithConstructor() throws Exception {\n\t\tStaticAndInstanceDemo staticAndInstanceDemoMock = createMock(StaticAndInstanceDemo.class);\n\n\t\tStaticAndInstanceWithConstructorCodeDemo tested = new StaticAndInstanceWithConstructorCodeDemo(\n\t\t\t\tstaticAndInstanceDemoMock);\n\n\t\tniceReplayAndVerify();\n\n\t\tmockStaticPartial(StaticAndInstanceDemo.class, \"getStaticMessage\");\n\n\t\tfinal String instanceExpected = \"value\";\n\t\texpect(staticAndInstanceDemoMock.getMessage()).andReturn(\n\t\t\t\tinstanceExpected);\n\n\t\tfinal String staticExpected = \"a static message\";\n\t\texpect(StaticAndInstanceDemo.getStaticMessage()).andReturn(\n\t\t\t\tstaticExpected);\n\n\t\treplay(StaticAndInstanceDemo.class, staticAndInstanceDemoMock, tested);\n\n\t\tString actual = tested.getMessage();\n\n\t\tverify(StaticAndInstanceDemo.class, staticAndInstanceDemoMock, tested);\n\n\t\tassertEquals(staticExpected + instanceExpected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/AbstractStaticInitializerTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.staticinitializer;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticinitializer.AbstractStaticInitializerExample;\n\nimport static org.junit.Assert.assertEquals;\n\n@RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor(\"samples.staticinitializer.AbstractStaticInitializerExample\")\npublic class AbstractStaticInitializerTest {\n\n\t@Test\n\tpublic void suppressStaticInitializerInAbstractClass() throws Exception {\n\t\tassertEquals(\"something\", AbstractStaticInitializerExample.getStaticString());\n\t}\n\n    @Test\n\tpublic void suppressStaticInitializerInAbstractClassWhenInstantiated() throws Exception {\n        AbstractStaticInitializerExample tested = new AbstractStaticInitializerExample() {};\n\t\tassertEquals(\"something\", tested.getString());\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/EvilStaticInitializerExampleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.staticinitializer;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticinitializer.EvilStaticInitializerExample;\n\nimport static org.hamcrest.core.IsInstanceOf.instanceOf;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.fail;\n\n/**\n * Test that demonstrates a (naive) example of when chunking may be handy.\n */\n@RunWith(PowerMockRunner.class)\npublic class EvilStaticInitializerExampleTest {\n\n\t@Test\n\t@SuppressStaticInitializationFor(\"samples.staticinitializer.EvilStaticInitializerExample\")\n    public void assertNativeCodeInvocationWorks() {\n\t\tEvilStaticInitializerExample tested = new EvilStaticInitializerExample();\n\t\tassertThat(tested.doSomeNativeStuffUsingTheLoadedSystemLibrary(), instanceOf(String.class));\n\t}\n\n\t@Test\n    public void assertCorrectErrorMessageIfLibraryNotFound() {\n\t\ttry {\n\t\t\tnew EvilStaticInitializerExample();\n\t\t\tfail(\"Should throw unsatisfied link error!\");\n\t\t} catch (UnsatisfiedLinkError error) {\n\t\t\tassertEquals(error.getMessage(), EvilStaticInitializerExample.FAILED_TO_LOAD_LIBRARY_MESSAGE);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/InterfaceStaticInitializerExampleTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.staticinitializer;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticinitializer.InterfaceComputation;\n\nimport static org.junit.Assert.assertEquals;\n\n@RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor( { \"samples.staticinitializer.InterfaceA\", \"samples.staticinitializer.InterfaceB\",\n\t\t\"samples.staticinitializer.InterfaceC\" })\npublic class InterfaceStaticInitializerExampleTest {\n\n\t@Test\n\tpublic void testSupressStaticInitializer() throws Exception {\n\t\tassertEquals(0, InterfaceComputation.calculateWithinHierarchy());\n\t}\n\n\t@Test\n\tpublic void testSupressStaticInitializer2() throws Exception {\n\t\tassertEquals(0, InterfaceComputation.calculateWithReference());\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/StaticInitializerExampleTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.staticinitializer;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.staticinitializer.StaticInitializerExample;\n\nimport java.util.HashSet;\n\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertSame;\n\n@RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor(\"samples.staticinitializer.StaticInitializerExample\")\npublic class StaticInitializerExampleTest {\n\n\t@Test\n\tpublic void testSupressStaticInitializerAndSetFinalField() throws Exception {\n\t\tassertNull(\"Should be null because the static initializer should be suppressed\", StaticInitializerExample.getMySet());\n\t\tfinal HashSet<String> hashSet = new HashSet<String>();\n\t\tWhitebox.setInternalState(StaticInitializerExample.class, \"mySet\", hashSet);\n\t\tassertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, \"mySet\"));\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/strict/StrictDemoTest.java",
    "content": "package samples.junit4.strict;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.strict.StrictDemo;\n\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * This is a simple test case for the {@link StrictDemo} class that demonstrates\n * that strict method mocking works.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StrictDemo.class)\npublic class StrictDemoTest {\n\n\t@Test\n\tpublic void testCallB_notStrict() throws Exception {\n\t\tStrictDemo tested = createPartialMock(StrictDemo.class, \"A\", \"B\");\n\t\texpectPrivate(tested, \"B\").times(1);\n\t\texpectPrivate(tested, \"A\").times(1);\n\n\t\treplay(tested);\n\n\t\ttested.callAThenB();\n\n\t\tverify(tested);\n\t}\n\n\t@Test(expected = AssertionError.class)\n\tpublic void testCallB_strict_failure() throws Exception {\n\t\tStrictDemo tested = createStrictPartialMock(StrictDemo.class, \"A\", \"B\");\n\t\texpectPrivate(tested, \"B\").times(1);\n\t\texpectPrivate(tested, \"A\").times(1);\n\n\t\treplay(tested);\n\n\t\ttested.callAThenB();\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testCallB_strict_ok() throws Exception {\n\t\tStrictDemo tested = createStrictPartialMock(StrictDemo.class, \"A\", \"B\");\n\t\texpectPrivate(tested, \"A\").times(1);\n\t\texpectPrivate(tested, \"B\").times(1);\n\n\t\treplay(tested);\n\n\t\ttested.callAThenB();\n\n\t\tverify(tested);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/stubmethod/StubMethodTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.stubmethod;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\nimport samples.suppressmethod.SuppressMethod;\n\nimport static junit.framework.Assert.fail;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.stub;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SuppressMethod.class)\npublic class StubMethodTest {\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expectedValue = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObject\")).toReturn(expectedValue);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\tassertEquals(expectedValue, tested.getObject());\n\t\tassertEquals(expectedValue, tested.getObject());\n\t}\n\n\t@Test\n\tpublic void whenStubbingStaticMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expectedValue = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObjectStatic\")).toReturn(expectedValue);\n\n\t\tassertEquals(expectedValue, SuppressMethod.getObjectStatic());\n\t\tassertEquals(expectedValue, SuppressMethod.getObjectStatic());\n\t}\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodWithPrimiteValueTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tfloat expectedValue = 4;\n\t\tstub(method(SuppressMethod.class, \"getFloat\")).toReturn(expectedValue);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\tassertEquals(expectedValue, tested.getFloat(), 0.0f);\n\t\tassertEquals(expectedValue, tested.getFloat(), 0.0f);\n\t}\n\n\t@Test(expected = TooManyMethodsFoundException.class)\n\tpublic void whenSeveralMethodsFoundThenTooManyMethodsFoundExceptionIsThrown() throws Exception {\n\t\tstub(method(SuppressMethod.class, \"sameName\"));\n\t}\n\n\t@Test(expected = MethodNotFoundException.class)\n\tpublic void whenNoMethodsFoundThenMethodNotFoundExceptionIsThrown() throws Exception {\n\t\tstub(method(SuppressMethod.class, \"notFound\"));\n\t}\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expected = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObject\")).toReturn(expected);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\tassertEquals(expected, tested.getObject());\n\t\tassertEquals(expected, tested.getObject());\n\t}\n\n\t@Test\n\tpublic void whenStubbingStaticMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expected = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObjectStatic\")).toReturn(expected);\n\n\t\tassertEquals(expected, SuppressMethod.getObjectStatic());\n\t\tassertEquals(expected, SuppressMethod.getObjectStatic());\n\t}\n\n\t@Test(expected = ClassCastException.class)\n\tpublic void whenStubbingInstanceMethodWithWrongReturnTypeThenClasscastExceptionIsThrown() throws Exception {\n\t\tString illegalReturnType = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getFloat\")).toReturn(illegalReturnType);\n\t\tSuppressMethod tested = new SuppressMethod();\n\t\ttested.getFloat();\n\t}\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception {\n\t\tException expected = new Exception(\"message\");\n\t\tstub(method(SuppressMethod.class, \"getObject\")).toThrow(expected);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\ttry {\n\t\t\ttested.getObject();\n\t\t\tfail();\n\t\t} catch (Exception e) {\n\t\t\tassertEquals(\"message\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void whenStubbingStaticMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception {\n\t\tException expected = new Exception(\"message\");\n\t\tstub(method(SuppressMethod.class, \"getObjectStatic\")).toThrow(expected);\n\t\ttry {\n\t\t\tSuppressMethod.getObjectStatic();\n\t\t\tfail();\n\t\t} catch (Exception e) {\n\t\t\tassertEquals(\"message\", e.getMessage());\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/CreateUnmockedTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.suppressconstructor;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.PowerMock;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.suppressconstructor.SuppressConstructorDemo;\nimport samples.suppressconstructor.SuppressSpecificConstructorDemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\n\n@RunWith(PowerMockRunner.class)\npublic class CreateUnmockedTest {\n\n\t@Test\n\tpublic void testUnmockedWithNoConstructorAndReplayVerify() throws Exception {\n\t\tSuppressSpecificConstructorDemo object = Whitebox.newInstance(SuppressSpecificConstructorDemo.class);\n\t\tPowerMock.niceReplayAndVerify();\n\t\tPowerMock.replay(object);\n\n\t\tassertEquals(\"Hello\", object.getHello());\n\n\t\tPowerMock.verify(object);\n\t}\n\n\t@Test\n\tpublic void testUnmockedWithConstructorAndAllowReplay() throws Exception {\n\t\tPowerMock.niceReplayAndVerify();\n\t\tSuppressConstructorDemo object = new SuppressConstructorDemo(\"Hello\");\n\t\tPowerMock.replay(object);\n\n\t\tassertEquals(\"Hello\", object.getMessage());\n\n\t\tPowerMock.verify(object);\n\t}\n\n\t@Test\n\tpublic void testUnmockedWithReplayCausesException() throws Exception {\n\t\tSuppressConstructorDemo object = new SuppressConstructorDemo(\"Hello\");\n\t\ttry {\n\t\t\tPowerMock.replay(object);\n\t\t\tfail(\"Replay should only work on mocks\");\n\t\t} catch (RuntimeException e) {\n\t\t\t// ignore\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.suppressconstructor;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.PowerMock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.suppressconstructor.SuppressConstructorDemo;\nimport samples.suppressconstructor.SuppressConstructorSubclassDemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.powermock.api.easymock.PowerMock.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n/**\n * This test demonstrates how to tell PowerMock to avoid executing constructor\n * code for a certain class. This is crucial in certain tests where the\n * constructor or a subclass's constructor performs operations that are of no\n * concern to the unit test of the actual class or if the constructor performs\n * operations, such as getting services from a runtime environment that has not\n * been initialized. In normal situations you're forced to create an integration\n * or function test for the class instead (and thus the runtime environment is\n * available). This is not particularly good when it comes to testing method\n * logic. PowerMock solves these problems by letting you specify the\n * {@link PowerMock#suppressConstructor(Class...)} method\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SuppressConstructorDemo.class)\npublic class SuppressConstructorDemoTest {\n\n    /**\n     * This test makes sure that the real constructor has never been called.\n     */\n    @Test\n    public void testSuppressConstructor() throws Exception {\n        suppress(constructor(SuppressConstructorDemo.class));\n        final SuppressConstructorDemo tested = new SuppressConstructorDemo(\"a message\");\n        assertNull(\"Message should have been null since we're skipping the execution of the constructor code.\", tested.getMessage());\n    }\n\n    /**\n     * This test makes sure that the real parent constructor has never been\n     * called.\n     */\n    @Test\n    public void testSuppressParentConstructor() throws Exception {\n        suppress(constructor(SuppressConstructorSubclassDemo.class));\n        final SuppressConstructorDemo tested = new SuppressConstructorDemo(\"a message\");\n        assertNull(\"Message should have been null since we're skipping the execution of the constructor code.\", tested.getMessage());\n    }\n\n    /**\n     * This test makes sure that it's possible to also mock methods from the\n     * class under test at the same time as skipping constructor execution.\n     */\n    @Test\n    public void testPartialMockingAndSuppressParentConstructor() throws Exception {\n        suppress(constructor(SuppressConstructorSubclassDemo.class));\n        final SuppressConstructorDemo tested = createPartialMock(SuppressConstructorDemo.class, \"returnAMessage\");\n        final String expected = \"Hello world!\";\n        expectPrivate(tested, \"returnAMessage\").andReturn(expected);\n        replay(tested);\n\n        final String actual = tested.getMyOwnMessage();\n\n        verify(tested);\n\n        assertEquals(expected, actual);\n\n        assertNull(\"Message should have been null since we're skipping the execution of the constructor code.\", tested.getMessage());\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorHierarchyDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.suppressconstructor;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.suppressconstructor.InvokeConstructor;\nimport samples.suppressconstructor.SuppressConstructorHierarchy;\n\nimport static org.junit.Assert.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@PrepareForTest(SuppressConstructorHierarchy.class)\n@RunWith(PowerMockRunner.class)\npublic class SuppressConstructorHierarchyDemoTest {\n\n\t@Test\n\tpublic void testSuppressConstructorHierarchy() throws Exception {\n\t\tsuppress(constructor(SuppressConstructorHierarchy.class));\n\t\tfinal String message = new InvokeConstructor().doStuff(\"qwe\");\n\t\tassertNull(\"Message should have been null since we're skipping the execution of the constructor code. Message was \\\"\" + message + \"\\\".\",\n\t\t\t\tmessage);\n\t}\n\n\t@Test\n\t@PrepareForTest\n\tpublic void testNotSuppressConstructorWithoutByteCodeManipulation() throws Exception {\n\t\ttry {\n\t\t\tnew SuppressConstructorHierarchy(\"message\");\n\t\t\tfail(\"Should throw RuntimeException since we're running this test with a new class loader!\");\n\t\t} catch (RuntimeException e) {\n\t\t\tassertEquals(\"This should be suppressed!!\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testNotSuppressConstructorWithByteCodeManipulation() throws Exception {\n\t\ttry {\n\t\t\tnew SuppressConstructorHierarchy(\"message\");\n\t\t\tfail(\"Should throw RuntimeException since we're running this test with a new class loader!\");\n\t\t} catch (RuntimeException e) {\n\t\t\tassertEquals(\"This should be suppressed!!\", e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * This simple test demonstrate that it's possible to continue execution\n\t * with the default {@code PrepareForTest} settings (i.e. using a\n\t * byte-code manipulated version of the SuppressConstructorHierarchyDemo\n\t * class).\n\t */\n\t@Test\n\tpublic void testSuppressConstructorHierarchyAgain() throws Exception {\n\t\tsuppress(constructor(SuppressConstructorHierarchy.class));\n\t\tSuppressConstructorHierarchy tested = new SuppressConstructorHierarchy(\"message\");\n\t\tassertEquals(42, tested.getNumber());\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressNonParentConstructorDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.suppressconstructor;\n\nimport org.junit.Test;\nimport org.powermock.reflect.Whitebox;\nimport samples.suppressconstructor.SuppressNonParentConstructorDemo;\n\nimport static org.junit.Assert.assertEquals;\n\npublic class SuppressNonParentConstructorDemoTest {\n\n\t@Test\n\tpublic void testNewInstanceWithoutInvokingConstructor() throws Exception {\n\t\tSuppressNonParentConstructorDemo constructorDemo = Whitebox\n\t\t\t\t.newInstance(SuppressNonParentConstructorDemo.class);\n\t\tassertEquals(\"Hello\", constructorDemo.getHello());\n\t}\n\n\t@Test(expected = IllegalStateException.class)\n\tpublic void testNewInstanceInvokingConstructor() throws Exception {\n\t\tnew SuppressNonParentConstructorDemo(\"failing\");\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/ItemRepositoryTest.java",
    "content": "package samples.junit4.suppressfield;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.suppressfield.ItemRepository;\n\nimport static org.powermock.api.support.membermodification.MemberMatcher.field;\nimport static org.powermock.api.support.membermodification.MemberMatcher.fields;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { ItemRepository.class })\n@SuppressStaticInitializationFor(\"samples.suppressfield.ItemRepository\")\npublic class ItemRepositoryTest {\n\t@Test(expected = NullPointerException.class)\n\tpublic void testaddItem() throws Exception {\n\t\tsuppress(fields(field(ItemRepository.class, \"itemMap\"), field(ItemRepository.class, \"totalItems\")));\n\n\t\tItemRepository objRep = Whitebox.newInstance(ItemRepository.class);\n\t\tobjRep.addItem(\"key\", \"value\");\n\t}\n}"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/SuppressFieldTest.java",
    "content": "package samples.junit4.suppressfield;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.suppressfield.SuppressField;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.powermock.api.support.membermodification.MemberMatcher.field;\nimport static org.powermock.api.support.membermodification.MemberMatcher.fields;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n/**\n * Unit tests that asserts that field suppression works.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SuppressField.class)\npublic class SuppressFieldTest {\n\n\t@Test\n\tpublic void assertThatSpecificStaticFinalFieldSuppressionWorks() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"MY_OBJECT\"));\n\t\tassertNull(SuppressField.getMyObject());\n\t}\n\n\t@Ignore(\"Final primitive types doesn't work, see issue at https://github.com/jayway/powermock/issues/105\")\n\t@Test\n\tpublic void assertThatSpecificStaticFinalPrimitiveFieldSuppressionWorks() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"MY_VALUE\"));\n\t\tassertEquals(0, SuppressField.getMyValue());\n\t}\n\n\t@Ignore(\"Final primitive types doesn't work, see issue at https://github.com/jayway/powermock/issues/105\")\n\t@Test\n\tpublic void assertThatSpecificInstanceFinalPrimitiveFieldSuppressionWorks() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"myBoolean\"));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertEquals(false, suppressField.isMyBoolean());\n\t}\n\n\t@Test\n\tpublic void assertThatSpecificInstanceFinalFieldSuppressionWorks() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"myWrappedBoolean\"));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertNull(suppressField.getMyWrappedBoolean());\n\t}\n\n\t@Test\n\tpublic void assertThatSpecificPrimitiveInstanceFieldSuppressionWorks() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"myChar\"));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertEquals(' ', suppressField.getMyChar());\n\t}\n\n\t@Test\n\tpublic void assertThatSpecificInstanceFieldSuppressionWorks() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"mySecondValue\"));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertNull(suppressField.getMySecondValue());\n\t}\n\n\t@Test\n\tpublic void assertThatSpecificInstanceFieldSuppressionWhenSpecifingClassAndFieldNameWorks() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"mySecondValue\"));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertNull(suppressField.getMySecondValue());\n\t}\n\n\t@Test\n\tpublic void assertThatMultipleInstanceFieldSuppressionWorks() throws Exception {\n\t\tsuppress(fields(SuppressField.class, \"mySecondValue\", \"myChar\"));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertNull(suppressField.getMySecondValue());\n\t\tassertEquals(' ', suppressField.getMyChar());\n\t\tassertEquals(Boolean.TRUE, suppressField.getMyWrappedBoolean());\n\t}\n\n\t// TODO Add final tests here as well when they work\n\t@Test\n\tpublic void assertThatAllFieldSuppressionWorks() throws Exception {\n\t\tsuppress(fields(SuppressField.class));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertNull(suppressField.getMySecondValue());\n\t\tassertEquals(' ', suppressField.getMyChar());\n\t\tassertNull(suppressField.getMyWrappedBoolean());\n\t\tassertNull(SuppressField.getMyObject());\n\t}\n\n\t@Test\n\tpublic void assertThatObjectIsNeverInstansiated() throws Exception {\n\t\tsuppress(field(SuppressField.class, \"domainObject\"));\n\t\tSuppressField suppressField = new SuppressField();\n\t\tassertNull(suppressField.getDomainObject());\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/suppressmethod/SuppressMethodTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.suppressmethod;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.StaticExample;\nimport samples.suppressmethod.SuppressMethod;\nimport samples.suppressmethod.SuppressMethodExample;\nimport samples.suppressmethod.SuppressMethodParent;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNull;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberMatcher.methods;\nimport static org.powermock.api.support.membermodification.MemberMatcher.methodsDeclaredIn;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { SuppressMethod.class, SuppressMethodExample.class, StaticExample.class })\npublic class SuppressMethodTest {\n\n    @Test\n    public void testGetObject() throws Exception {\n        suppress(method(SuppressMethod.class, \"getObject\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertNull(\"A method returning Object should return null after suppressing method code.\", tested.getObject());\n    }\n\n    @Test\n    public void testSuppressMultipleMethods() throws Exception {\n        suppress(methods(SuppressMethod.class, \"getObject\", \"getShort\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertNull(\"A method returning Object should return null after suppressing method code.\", tested.getObject());\n        assertEquals(\"A method returning a short should return 0 after suppressing method code.\", 0, tested.getShort());\n    }\n\n    @Test\n    public void testGetObjectStatic() throws Exception {\n        suppress(method(SuppressMethod.class, \"getObjectStatic\"));\n\n        assertNull(\"A method returning Object should return null after suppressing method code.\", SuppressMethod\n                .getObjectStatic());\n    }\n\n    @Test\n    public void testGetByte() throws Exception {\n        suppress(method(SuppressMethod.class, \"getByte\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(\"A method returning a byte should return 0 after suppressing method code.\", 0, tested.getByte());\n    }\n\n    @Test\n    public void testGetShort() throws Exception {\n        suppress(method(SuppressMethod.class, \"getShort\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(\"A method returning a short should return 0 after suppressing method code.\", 0, tested.getShort());\n    }\n\n    @Test\n    public void testGetInt() throws Exception {\n        suppress(method(SuppressMethod.class, \"getInt\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(\"A method returning an int should return 0 after suppressing method code.\", 0, tested.getInt());\n    }\n\n    @Test\n    public void testGetLong() throws Exception {\n        suppress(method(SuppressMethod.class, \"getLong\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(\"A method returning a long should return 0 after suppressing method code.\", 0, tested.getLong());\n    }\n\n    @Test\n    public void testGetBoolean() throws Exception {\n        suppress(method(SuppressMethod.class, \"getBoolean\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertFalse(\"A method returning a boolean should return false after suppressing method code.\", tested\n                .getBoolean());\n    }\n\n    @Test\n    public void testGetFloat() throws Exception {\n        suppress(method(SuppressMethod.class, \"getFloat\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(\"A method returning a float should return 0.0f after suppressing method code.\", 0.0f, tested\n                .getFloat(), 0);\n    }\n\n    @Test\n    public void testGetDouble() throws Exception {\n        suppress(method(SuppressMethod.class, \"getDouble\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(\"A method returning a double should return 0.0d after suppressing method code.\", 0.0d, tested\n                .getDouble(), 0);\n    }\n\n    @Test\n    public void testGetDouble_parameter() throws Exception {\n        suppress(method(SuppressMethod.class, \"getDouble\", new Class<?>[] { double.class }));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(\"A method returning a double should return 0.0d after suppressing method code.\", 0.0d, tested\n                .getDouble(8.7d), 0);\n    }\n\n    @Test\n    public void testInvokeVoid() throws Exception {\n        suppress(method(SuppressMethod.class, \"invokeVoid\", new Class<?>[] { StringBuilder.class }));\n\n        SuppressMethod tested = new SuppressMethod();\n        // Should not cause an NPE when suppressing code.\n        tested.invokeVoid(null);\n    }\n\n    @Test\n    public void testInvokeVoid_noParameterTypeSupplied() throws Exception {\n        suppress(method(SuppressMethod.class, \"invokeVoid\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        // Should not cause an NPE when suppressing code.\n        tested.invokeVoid(null);\n    }\n\n    @Test\n    public void suppressAllMethodsInMultipleClasses() throws Exception {\n        suppress(methodsDeclaredIn(SuppressMethod.class, SuppressMethodExample.class));\n\n        SuppressMethod tested1 = new SuppressMethod();\n        SuppressMethodExample tested2 = new SuppressMethodExample();\n        // Should not cause an NPE when suppressing code.\n        tested1.invokeVoid(null);\n\n        assertNull(tested1.getObject());\n        assertEquals(0, tested1.getInt());\n        assertNull(tested2.getObject());\n    }\n\n    @Test\n    public void suppressPublicStaticMethod() throws Exception {\n        suppress(method(StaticExample.class, \"staticVoidMethod\"));\n\n        StaticExample.staticVoidMethod();\n    }\n\n    @Test\n    public void suppressOverridingMethod() throws Exception {\n        suppress(method(SuppressMethod.class, \"myMethod\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(0, tested.myMethod());\n    }\n\n    @Test\n    public void testSuppressMethodInParentOnly() throws Exception {\n        suppress(method(SuppressMethodParent.class, \"myMethod\"));\n\n        SuppressMethod tested = new SuppressMethod();\n        assertEquals(20, tested.myMethod());\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/swing/ReallySimpleSwingDemoTest.java",
    "content": "package samples.junit4.swing;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.swing.ReallySimpleSwingDemo;\n\nimport javax.swing.*;\n\nimport static org.junit.Assume.assumeTrue;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Unit test that makes sure that PowerMock works with Swing components.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(JOptionPane.class)\npublic class ReallySimpleSwingDemoTest {\n\n\t@Test\n\tpublic void assertThatPowerMockWorksWithSwingComponents() throws Exception {\n        // Currently this tests fails on Java 8, see issue 504.\n        assumeTrue(Float.valueOf(System.getProperty(\"java.specification.version\")) < 1.8f);\n\n\t\tfinal String message = \"powermock\";\n\n\t\tmockStatic(JOptionPane.class);\n\n\t\tJOptionPane.showMessageDialog(null, message);\n\t\texpectLastCall().once();\n\n\t\treplayAll();\n\n\t\tnew ReallySimpleSwingDemo().displayMessage(message);\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/system/FieldMockDefect.java",
    "content": "package samples.junit4.system;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.lang.reflect.Field;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * \n * The reason why it fails is because we create a new instance of the field\n * using Whitebox but then hashCode doesn't work because it's missing\n * constructor args.\n * <p>\n * \n * if (Field.class.isAssignableFrom(mock.getClass())) {\n * Whitebox.setInternalState(mock, \"clazz\", (Object) Object.class);\n * Whitebox.setInternalState(mock, \"name\", Object.class.getName()); }\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(Field.class)\npublic class FieldMockDefect {\n    @Test\n    public void test() {\n        final Field fieldMock = createMock(Field.class);\n        expect(fieldMock.getName()).andReturn(\"foo\");\n        replayAll();\n        assertEquals(\"foo\", new ClassUnderTest().foo(fieldMock));\n        verifyAll();\n\n    }\n\n    private static final class ClassUnderTest {\n        public String foo(Field field) {\n            return field.getName();\n        }\n    }\n}"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/system/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.system;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.system.SystemClassUser;\n\nimport java.net.InetAddress;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.easymock.EasyMock.anyLong;\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.*;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Demonstrates PowerMock's ability to mock non-final and final system classes.\n * To mock a system class you need to prepare the calling class for testing.\n * I.e. let's say you're testing class A which interacts with URLEncoder then\n * you would do:\n *\n * <pre>\n *\n * &#064;PrepareForTest({A.class})\n *\n * </pre>\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { SystemClassUser.class })\npublic class SystemClassUserTest {\n\n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n\n        expect(URLEncoder.encode(\"string\", \"enc\")).andReturn(\"something\");\n        replayAll();\n\n        assertEquals(\"something\", new SystemClassUser().performEncode());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n\n        Runtime runtimeMock = createMock(Runtime.class);\n        Process processMock = createMock(Process.class);\n\n        expect(Runtime.getRuntime()).andReturn(runtimeMock);\n        expect(runtimeMock.exec(\"command\")).andReturn(processMock);\n\n        replayAll();\n\n        assertSame(processMock, new SystemClassUser().executeCommand());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n\n        expect(System.getProperty(\"property\")).andReturn(\"my property\");\n\n        replayAll();\n\n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStaticPartial(System.class, \"nanoTime\");\n\n        expect(System.nanoTime()).andReturn(2L);\n\n        replayAll();\n\n        new SystemClassUser().doMoreComplicatedStuff();\n\n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n\n        Collections.shuffle(list);\n        expectLastCall().once();\n\n        replayAll();\n\n        new SystemClassUser().shuffleCollection(list);\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        mockStaticPartial(System.class, \"getProperty\");\n\n        expect(System.getProperty(\"property\")).andReturn(\"my property\");\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n\n        expect(String.format(string, args)).andReturn(returnValue);\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingStaticVoidMethodWorks() throws Exception {\n        mockStatic(Thread.class);\n\n        Thread.sleep(anyLong());\n        expectLastCall().once();\n\n        replayAll();\n\n        long startTime = System.currentTimeMillis();\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.threadSleep();\n        long endTime = System.currentTimeMillis();\n        assertTrue(endTime - startTime < 5000);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingInstanceMethodOfFinalSystemClassWorks() throws Exception {\n        URL url = createMock(URL.class);\n        URLConnection urlConnection = createMock(URLConnection.class);\n\n        expect(url.openConnection()).andStubReturn(urlConnection);\n\n        replayAll();\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertSame(urlConnection, systemClassUser.useURL(url));\n        verifyAll();\n    }\n\n    @Test\n    public void mockingURLWorks() throws Exception {\n        URL url = createMock(URL.class);\n        URLConnection urlConnectionMock = createMock(URLConnection.class);\n\n        expect(url.openConnection()).andReturn(urlConnectionMock);\n\n        replayAll();\n\n        assertSame(url.openConnection(), urlConnectionMock);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingFinalMethodsInSystemClassesWorks() throws Exception {\n        ClassLoader cl1 = createMock(ClassLoader.class);\n        ClassLoader cl2 = createMock(ClassLoader.class);\n\n        expect(cl1.getParent()).andReturn(cl2);\n\n        replayAll();\n\n        assertSame(cl1.getParent(), cl2);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingInetAddressWorks() throws Exception {\n        final InetAddress mock = createMock(InetAddress.class);\n        mockStatic(InetAddress.class);\n\n        expect(InetAddress.getLocalHost()).andReturn(mock);\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertSame(mock, systemClassUser.getLocalHost());\n\n        verifyAll();\n    }\n}"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/RunWithHierarchyTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.testhierarchy;\n\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport samples.finalmocking.FinalDemo;\n\n//@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class RunWithHierarchyTest extends TestParent {\n\t\n\t@Test\n\tpublic void testname() throws Exception {\n\t\t\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/TestParent.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.testhierarchy;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n@RunWith(PowerMockRunner.class)\npublic abstract class TestParent {\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/verify/AssertVerifyWorksTest.java",
    "content": "package samples.junit4.verify;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * This test asserts that the\n * http://code.google.com/p/powermock/issues/detail?id=73 issue is resolved.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticHelper.class, StaticService.class })\npublic class AssertVerifyWorksTest {\n\n\t@Test\n\tpublic void testMockStaticWorks() throws Exception {\n\t\tmockStaticPartial(StaticService.class, \"sayHello\");\n\t\tmockStatic(StaticHelper.class);\n\n\t\tStaticService.sayHello();\n\t\texpectLastCall().once();\n\n\t\tStaticHelper.sayHelloHelper();\n\t\texpectLastCall().once();\n\n\t\treplay(StaticService.class);\n\t\treplay(StaticHelper.class);\n\n\t\tStaticService.assertThatVerifyWorksForMultipleMocks();\n\n\t\tverify(StaticService.class);\n\t\tverify(StaticHelper.class);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/junit4/whitebox/PowerMockConstructorFiltrationTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.whitebox;\n\nimport org.junit.Test;\nimport org.powermock.reflect.internal.WhiteboxImpl;\nimport samples.whitebox.ClassWithPowerMockGeneratedConstructor;\n\nimport java.lang.reflect.Constructor;\n\nimport static org.junit.Assert.assertEquals;\n\npublic class PowerMockConstructorFiltrationTest {\n\t@Test\n\tpublic void findUniqueConstructorOrThrowExceptionFiltersPowerMockConstructors() throws Exception {\n\t\tConstructor<?> actualConstructor = WhiteboxImpl.findUniqueConstructorOrThrowException(ClassWithPowerMockGeneratedConstructor.class,\n\t\t\t\t(Object) null);\n\t\tassertEquals(ClassWithPowerMockGeneratedConstructor.class.getConstructor(String.class), actualConstructor);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/methodhierarchy/MethodInvocationDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.methodhierarchy;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test that verifies that it's possible to invoke and create partial mocks of\n * private and/protected methods in a hierarchy.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MethodInvocationDemo.class })\npublic class MethodInvocationDemoTest {\n\n\t@Test\n\tpublic void testCreatePartialMockForAProtectedMethodInASubclass() throws Exception {\n\t\tfinal String value = \"another string\";\n\t\tfinal String getTheStringMethodName = \"getTheString\";\n\t\tMethodInvocationDemo tested = createPartialMock(MethodInvocationDemo.class, getTheStringMethodName);\n\n\t\texpect(tested.getTheString()).andReturn(value);\n\n\t\treplay(tested);\n\n\t\tassertEquals(value, Whitebox.invokeMethod(tested, \"getString\"));\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\t@Ignore(\"Mabey this is impossible to achieve\")\n\tpublic void testCreatePartialMockForAProtectedMethodInASpecificSubclass() throws Exception {\n\t\tfinal String value = \"another string\";\n\t\tfinal String getTheStringMethodName = \"getTheString\";\n\t\tMethodInvocationDemo tested = createPartialMock(MethodInvocationDemo.class, MethodInvocationDemoGrandParent.class, getTheStringMethodName);\n\n\t\texpectPrivate(tested, getTheStringMethodName, MethodInvocationDemoGrandParent.class).andReturn(value);\n\n\t\treplay(tested);\n\n\t\tassertEquals(\"MethodInvocationDemoParent wrapped \" + value, tested.getTheString());\n\n\t\tverify(tested);\n\t}\n\n\t@Test\n\tpublic void testWhenClassUnderTestIsAnAnonymousInnerClass() throws Exception {\n\t\tMethodInvocationDemo tested = new MethodInvocationDemo() {\n\n\t\t};\n\n\t\tassertEquals(\"MethodInvocationDemoParent wrapped a string from MethodInvocationDemoGrandParent\", Whitebox.invokeMethod(tested, \"getString\"));\n\t}\n\n\t@Test\n\tpublic void testInvokePrivateMethodInSuperClassWhenClassUnderTestIsAnAnonymousInnerClass() throws Exception {\n\t\tMethodInvocationDemo tested = new MethodInvocationDemo() {\n\n\t\t};\n\n\t\tassertEquals(\"MethodInvocationDemoParent\", Whitebox.invokeMethod(tested, MethodInvocationDemoParent.class, \"getString\"));\n\t}\n\n\t@Test\n\tpublic void testInvokeProtectedMethodWhenClassUnderTestIsAnAnonymousInnerClass() throws Exception {\n\t\tMethodInvocationDemo tested = new MethodInvocationDemo() {\n\n\t\t};\n\n\t\tassertEquals(\"MethodInvocationDemoParent wrapped a string from MethodInvocationDemoGrandParent\", tested.getTheString());\n\t}\n\n\t@Test\n\tpublic void testInvokeProtectedMethodWhenClassUnderTestIsAnAnonymousInnerClassUsingWithbox() throws Exception {\n\t\tMethodInvocationDemo tested = new MethodInvocationDemo() {\n\n\t\t};\n\n\t\tassertEquals(\"MethodInvocationDemoParent wrapped a string from MethodInvocationDemoGrandParent\", Whitebox.invokeMethod(tested, \"getTheString\"));\n\t}\n\n\t@Test\n\tpublic void testInvokeSpecificMethodInHierarchy() throws Exception {\n\t\tMethodInvocationDemo tested = new MethodInvocationDemo();\n\n\t\tassertEquals(\"MethodInvocationDemoGrandParent\", Whitebox.invokeMethod(tested, MethodInvocationDemoGrandParent.class, \"getString\",\n\t\t\t\t(Object[]) new Class<?>[0]));\n\t}\n\n\t@Test\n\tpublic void testInvokeSpecificMethodInHierarchyWithArguments() throws Exception {\n\t\tMethodInvocationDemo tested = new MethodInvocationDemo();\n\n\t\tassertEquals(\"MethodInvocationDemoGrandParent: 2\", Whitebox.invokeMethod(tested, MethodInvocationDemoGrandParent.class, \"getString\",\n\t\t\t\tnew Class<?>[] { int.class }, 2));\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/packageprivate/PackagePrivateClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.packageprivate;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Verifies that the issue at\n * http://code.google.com/p/powermock/issues/detail?id=32 is solved.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PackagePrivateClass.class)\npublic class PackagePrivateClassTest {\n\n\t@Test\n\tpublic void testMockAPackagePrivateClass() throws Exception {\n\t\tfinal String returnAValueMethodName = \"returnAValue\";\n\t\tfinal int expected = 23;\n\n\t\tPackagePrivateClass tested = createPartialMock(PackagePrivateClass.class, returnAValueMethodName);\n\t\texpectPrivate(tested, returnAValueMethodName).andReturn(expected);\n\n\t\treplay(tested);\n\n\t\tassertEquals(expected, tested.getValue());\n\n\t\tverify(tested);\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressDefaultConstructorTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.suppressconstructor;\n\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static junit.framework.Assert.assertEquals;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberMatcher.defaultConstructorIn;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(AppaleList.class)\npublic class SuppressDefaultConstructorTest {\n\n\t@Test\n\tpublic void powerMockCanSuppressDefaultConstructor() {\n\t\tsuppress(defaultConstructorIn(AppaleList.class));\n\t\tAppaleList appaleList = new AppaleList();\n\t\tString str = appaleList.getAll();\n\t\tassertEquals(str, \"str\");\n\t}\n\n\t@Test(expected = IllegalArgumentException.class)\n\tpublic void powerMockSuppressesOnlyDefaultConstructorWhenUsingDefaultConstructorIn() {\n\t\tsuppress(defaultConstructorIn(AppaleList.class));\n\t\tnew AppaleList(\"something\");\n\t}\n\n    @Test\n\tpublic void powerMockCanSuppressDefaultConstructorUsingConstructorMethod() {\n\t\tsuppress(constructor(AppaleList.class, new Class[0]));\n\t\tAppaleList appaleList = new AppaleList();\n\t\tString str = appaleList.getAll();\n\t\tassertEquals(str, \"str\");\n\t}\n\n    @Test(expected = IllegalArgumentException.class)\n\tpublic void powerMockSuppressesOnlyDefaultConstructorWhenApplicable() {\n\t\tsuppress(constructor(AppaleList.class, new Class[0]));\n\t\tnew AppaleList(\"something\");\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressSpecificConstructorDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { SuppressSpecificConstructorDemo.class, SuppressSpecificConstructorDemoTest.class })\npublic class SuppressSpecificConstructorDemoTest {\n\n\t@Test\n\tpublic void testMockStringConstructor() throws Exception {\n\t\tsuppress(constructor(SuppressSpecificConstructorDemo.class, String.class));\n\n\t\t// This should be fine\n\t\tnew SuppressSpecificConstructorDemo(\"This expection should not occur\");\n\t\t// This should not be fine!\n\t\ttry {\n\t\t\tnew SuppressSpecificConstructorDemo();\n\t\t\tfail(\"Should have thrown IllegalStateException!\");\n\t\t} catch (IllegalStateException e) {\n\t\t\t// assertEquals(\"\", e.getMessage());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.agent;\n\nimport org.easymock.Mock;\nimport org.easymock.TestSubject;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport java.util.Arrays;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.replay;\n\n@RunWith(Parameterized.class)\npublic class AnnotationUsageTest {\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n\n\n    @TestSubject\n    private final\n    AnnotationDemo tested = new AnnotationDemo();\n\n\n    @SuppressWarnings(\"unused\")\n    @Mock\n    private Service server;\n\n    private final String fooId;\n\n\n    public AnnotationUsageTest(String fooId) {\n        this.fooId = fooId;\n    }\n\n\n    @Parameterized.Parameters()\n    public static Iterable<Object[]> data() {\n        return Arrays.asList(new Object[][]{\n                {\"1\"},\n                {\"2\"}\n        });\n    }\n\n\n    @Before\n    public void setUp() {\n        expect(server.getServiceMessage()).andReturn(fooId);\n        replay(server);\n    }\n\n    @Test\n    public void annotationsAreEnabledWhenUsingTheJUnitRule() {\n        String serviceMessage = tested.getServiceMessage();\n        assertEquals(fooId, serviceMessage);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java",
    "content": "package samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.largemethod.MethodExceedingJvmLimit;\n\nimport static junit.framework.Assert.assertEquals;\nimport static junit.framework.Assert.assertNull;\nimport static junit.framework.Assert.assertSame;\nimport static junit.framework.Assert.assertTrue;\nimport static junit.framework.Assert.fail;\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.method;\nimport static org.powermock.api.easymock.PowerMock.mockStatic;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.suppress;\n\n@PrepareForTest(MethodExceedingJvmLimit.class)\npublic class LargeMethodTest {\n\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    @Test\n    public void largeMethodShouldBeOverridden() {\n        try {\n            MethodExceedingJvmLimit.init();\n            fail(\"Method should be overridden and exception should be thrown\");\n        } catch (Exception e) {\n            assertSame(IllegalAccessException.class, e.getClass());\n            assertTrue(e.getMessage().contains(\"Method was too large and after instrumentation exceeded JVM limit\"));\n        }\n    }\n\n    @Test\n    public void largeMethodShouldBeAbleToBeSuppressed() {\n        suppress(method(MethodExceedingJvmLimit.class, \"init\"));\n        assertNull(\"Suppressed method should return: null\", MethodExceedingJvmLimit.init());\n    }\n\n    @Test\n    public void largeMethodShouldBeAbleToBeMocked() {\n        mockStatic(MethodExceedingJvmLimit.class);\n        expect(MethodExceedingJvmLimit.init()).andReturn(\"ok\");\n        replayAll();\n        assertEquals(\"Mocked method should return: ok\", \"ok\", MethodExceedingJvmLimit.init());\n    }\n\n    @Test(expected = IllegalStateException.class)\n    public void largeMethodShouldBeAbleToBeMockedAndThrowException() {\n        mockStatic(MethodExceedingJvmLimit.class);\n        expect(MethodExceedingJvmLimit.init()).andThrow(new IllegalStateException());\n        replayAll();\n        MethodExceedingJvmLimit.init();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/annotationbased/AnnotationDemoWithSetupMethodTest.java",
    "content": "package samples.junit4.legacy.annotationbased;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.modules.junit4.legacy.PowerMockRunner;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n/**\n * Verifies that PowerMock test listeners works correctly with setup methods.\n */\n@RunWith(PowerMockRunner.class)\npublic class AnnotationDemoWithSetupMethodTest {\n\n\t@Mock\n\tprivate Service serviceMock;\n\n\tprivate AnnotationDemo tested;\n\n\t@Before\n\tpublic void setup() {\n\t\ttested = new AnnotationDemo(serviceMock);\n\t}\n\n\t@Test\n\tpublic void assertInjectionWorked() throws Exception {\n\t\tfinal String expected = \"mock\";\n\t\texpect(serviceMock.getServiceMessage()).andReturn(expected);\n\n\t\treplayAll();\n\n\t\tassertEquals(expected, tested.getServiceMessage());\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/annotationbased/FinalDemoWithAnnotationInjectionTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.legacy.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.legacy.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate non-static final mocking.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class FinalDemoWithAnnotationInjectionTest {\n\n    @Mock\n    private FinalDemo tested;\n\n    @Test\n    public void testSay() throws Exception {\n        String expected = \"Hello altered World\";\n        expect(tested.say(\"hello\")).andReturn(\"Hello altered World\");\n        replay(tested);\n\n        String actual = tested.say(\"hello\");\n\n        verify(tested);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n\n        // Should still be mocked by now.\n        try {\n            tested.say(\"world\");\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected method call FinalDemo.say(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSayFinalNative() throws Exception {\n        String expected = \"Hello altered World\";\n        expect(tested.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n        replay(tested);\n\n        String actual = tested.sayFinalNative(\"hello\");\n\n        verify(tested);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n\n        // Should still be mocked by now.\n        try {\n            tested.sayFinalNative(\"world\");\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\"\\n  Unexpected method call FinalDemo.sayFinalNative(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/noannotation/NoAnnotationUsageTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.legacy.noannotation;\n\nimport junit.framework.TestCase;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.legacy.PowerMockRunner;\nimport samples.staticandinstance.StaticAndInstanceDemo;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test case that demonstrates the ability to run test cases not annotated with\n * {@link Test} when extending from {@link TestCase} using JUnit4 legacy\n * (4.0-4.3).\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class NoAnnotationUsageTest extends TestCase {\n\n\tpublic void testShouldMockPrivateAndStaticMethod() throws Exception {\n\t\tmockStaticPartial(StaticAndInstanceDemo.class, \"getStaticMessage\");\n\n\t\tStaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, \"getPrivateMessage\");\n\n\t\tfinal String staticExpected = \"a static message\";\n\t\texpect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected);\n\n\t\tfinal String privateExpected = \"A private message \";\n\t\texpectPrivate(tested, \"getPrivateMessage\").andReturn(privateExpected);\n\n\t\treplay(tested);\n\t\treplay(StaticAndInstanceDemo.class);\n\n        assertThat(tested.getMessage()).isEqualTo(privateExpected + staticExpected);\n\n        verify(tested);\n        verify(StaticAndInstanceDemo.class);\n\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java",
    "content": "package samples.junit4.legacy.noannotation;\n\nimport junit.framework.TestCase;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.legacy.PowerMockRunner;\n\n@RunWith(PowerMockRunner.class)\npublic class SetUpAndTearDownWhenExtendingTestCaseTest extends TestCase {\n\tprivate static final String INITIAL_MESSAGE = \"\";\n\tprivate static final String SET_UP_MESSAGE = \"setUp\";\n\tprivate static final String TEST_MESSAGE = \"test\";\n\n\tprivate static String CURRENT_MESSAGE = INITIAL_MESSAGE;\n\n\t@Override\n\tprotected void setUp() throws Exception {\n\t\tassertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE);\n\t\tCURRENT_MESSAGE = SET_UP_MESSAGE;\n\t}\n\n\t@Override\n\tprotected void tearDown() throws Exception {\n\t\tassertEquals(TEST_MESSAGE, CURRENT_MESSAGE);\n\t}\n\n\tpublic void testSomething() throws Exception {\n\t\tassertEquals(SET_UP_MESSAGE, CURRENT_MESSAGE);\n\t\tCURRENT_MESSAGE = TEST_MESSAGE;\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/noannotation/SetUpAndTearDownWhenNotExtendingTestCaseTest.java",
    "content": "package samples.junit4.legacy.noannotation;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.legacy.PowerMockRunner;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\n\n@RunWith(PowerMockRunner.class)\npublic class SetUpAndTearDownWhenNotExtendingTestCaseTest {\n\tprivate static final String INITIAL_MESSAGE = \"\";\n\tprivate static String CURRENT_MESSAGE = INITIAL_MESSAGE;\n\n\tpublic void setUp() throws Exception {\n\t\tfail(\"Should not call setUp\");\n\t}\n\n\tpublic void tearDown() throws Exception {\n\t\tfail(\"Should not call tearDown\");\n\t}\n\n\t@Test\n\tpublic void testSomething() throws Exception {\n\t\tassertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/singleton/MockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.legacy.singleton;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.legacy.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n * \n * @author Johan Haleby\n * @author Jan Kronquist\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticService.class, StaticHelper.class })\npublic class MockStaticTest {\n\n\t@Test\n\tpublic void testSay() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.say(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Singleton still be mocked by now.\n\t\ttry {\n\t\t\tStaticService.say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call StaticService.say(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testSayFinal() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayFinal(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayFinal(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Singleton still be mocked by now.\n\t\ttry {\n\t\t\tStaticService.sayFinal(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call StaticService.sayFinal(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testSayNative() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayNative(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void sayFinalNative() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayFinalNative(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\t}\n\n\t@Test\n\tpublic void mockAStaticMethod() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"qwe\";\n\t\texpect(StaticService.doStatic(5)).andReturn(expected);\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.doStatic(5);\n\t\tassertEquals(expected, actual);\n\t\tverify(StaticService.class);\n\t}\n\n\t@Test\n\tpublic void mockSayHello() throws Exception {\n\t\tmockStatic(StaticHelper.class);\n\t\tStaticHelper.sayHelloHelper();\n\t\texpectLastCall().times(2);\n\t\treplay(StaticHelper.class);\n\n\t\tStaticService.sayHello();\n\n\t\tverify(StaticHelper.class);\n\t}\n\n\t@Test\n\tpublic void mockSayHelloAgain() throws Exception {\n\t\tmockStatic(StaticHelper.class);\n\t\tStaticHelper.sayHelloAgain();\n\t\texpectLastCall().times(2);\n\t\treplay(StaticHelper.class);\n\n\t\tStaticService.sayHelloAgain();\n\n\t\tverify(StaticHelper.class);\n\t}\n\n\t@Test\n\tpublic void testSayPrivateStatic() throws Exception {\n\t\tmockStaticPartial(StaticService.class, \"sayPrivateStatic\", String.class);\n\n\t\tfinal String expected = \"Hello world\";\n\t\texpectPrivate(StaticService.class, \"sayPrivateStatic\", \"name\").andReturn(expected);\n\n\t\treplay(StaticService.class);\n\n\t\tString actual = Whitebox.invokeMethod(StaticService.class, \"sayPrivateStatic\", \"name\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void testSayPrivateFinalStatic() throws Exception {\n\t\tmockStaticPartial(StaticService.class, \"sayPrivateFinalStatic\", String.class);\n\n\t\tfinal String expected = \"Hello world\";\n\t\texpectPrivate(StaticService.class, \"sayPrivateFinalStatic\", \"name\").andReturn(expected);\n\n\t\treplay(StaticService.class);\n\n\t\tString actual = Whitebox.invokeMethod(StaticService.class, \"sayPrivateFinalStatic\", \"name\");\n\n\t\tverify(StaticService.class);\n\t\tassertEquals(expected, actual);\n\t}\n\n\t@Test\n\tpublic void innerClassesWork() {\n\t\tassertThat(StaticService.getNumberFromInner()).isEqualTo(17);\n\t}\n\n\t@Test\n\tpublic void innerInstanceClassesWork() {\n\t\tassertThat(StaticService.getNumberFromInnerInstance()).isEqualTo(23);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/suppressconstructor/SuppressConstructorHierarchyDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.legacy.suppressconstructor;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.legacy.PowerMockRunner;\nimport samples.suppressconstructor.SuppressConstructorHeirarchyEvilGrandParent;\nimport samples.suppressconstructor.SuppressConstructorHierarchy;\nimport samples.suppressconstructor.SuppressConstructorHierarchyParent;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@PrepareForTest( { SuppressConstructorHierarchy.class, SuppressConstructorHierarchyParent.class,\n\t\tSuppressConstructorHeirarchyEvilGrandParent.class })\n@RunWith(PowerMockRunner.class)\npublic class SuppressConstructorHierarchyDemoTest {\n\n\t@Test\n\tpublic void testSuppressConstructor() throws Exception {\n\t\tsuppress(constructor(SuppressConstructorHierarchy.class));\n\t\tSuppressConstructorHierarchy tested = new SuppressConstructorHierarchy(\"message\");\n\n\t\tfinal String message = tested.getMessage();\n\t\tassertNull(\"Message should have been null since we're skipping the execution of the constructor code. Message was \\\"\" + message + \"\\\".\",\n\t\t\t\tmessage);\n\t}\n\n\t@Test\n\t@PrepareForTest\n\tpublic void testNotSuppressConstructor() throws Exception {\n\t\ttry {\n\t\t\tnew SuppressConstructorHierarchy(\"message\");\n\t\t\tfail(\"Should throw RuntimeException since we're running this test with a new class loader!\");\n\t\t} catch (RuntimeException e) {\n\t\t\tassertEquals(\"This should be suppressed!!\", e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * This simple test demonstrate that it's possible to continue execution\n\t * with the default {@code PrepareForTest} settings (i.e. using a\n\t * byte-code manipulated version of the SuppressConstructorHierarchyDemo\n\t * class).\n\t */\n\t@Test\n\tpublic void testGetNumber() throws Exception {\n\t\tsuppress(constructor(SuppressConstructorHierarchy.class));\n\t\tSuppressConstructorHierarchy tested = new SuppressConstructorHierarchy(\"message\");\n\t\tassertThat(tested.getNumber()).isEqualTo(42);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/assume/AssumeForJUnit410Test.java",
    "content": "package samples.junit410.assume;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assume.assumeTrue;\n\n@RunWith(PowerMockRunner.class)\npublic class AssumeForJUnit410Test {\n\n    @Test\n    public void assumesWorkWithPowerMockForJUnit410() throws Exception {\n        // When\n        assumeTrue(false);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit410.expectnew;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.junit4.expectnew.ExpectNewCases;\nimport samples.newmocking.MyClass;\n\nimport java.io.DataInputStream;\n\n/**\n * Test class to demonstrate new instance mocking using expectNew(..).\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class })\npublic class ExpectNewDemoTest extends ExpectNewCases{\n\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewOfFinalSystemClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit410.expectnew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewOfFinalSystemClassDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class })\npublic class ExpectNewOfFinalSystemClassTest {\n\n    @Test\n    public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception {\n        String mock = createMock(String.class);\n\n        expectNew(String.class, \"My String\").andReturn(mock);\n        expect(mock.charAt(0)).andReturn('o');\n\n        replayAll();\n        assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar());\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/github668/Github668.java",
    "content": "package samples.junit410.github668;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.api.extension.listener.AnnotationEnabler;\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\n\n\n/**\n *\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockListener(AnnotationEnabler.class)\npublic class Github668 {\n\n    @Mock\n    private IncidentPropertyChangeDAO incidentPropertyChangeDAO;\n\n    @Test\n    public void mockClassShouldInjected() {\n        assertNotNull(incidentPropertyChangeDAO);\n    }\n    \n    @Test\n    public void shouldBeAbleMockMethodsOfInjected() {\n        expect(incidentPropertyChangeDAO.getIncident()).andReturn(\"value\");\n        replayAll(incidentPropertyChangeDAO);\n\n        assertEquals(\"value\",incidentPropertyChangeDAO.getIncident());\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/github668/IncidentPropertyChangeDAO.java",
    "content": "package samples.junit410.github668;\n\n/**\n *\n */\npublic interface IncidentPropertyChangeDAO {\n    String getIncident();\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/github668/package-info.java",
    "content": "/**\n *  \\@Mock fields are not injected anymore (1.6.5 regression)\n * https://github.com/jayway/powermock/issues/668\n */\npackage samples.junit410.github668;"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/rules/AssertThatJUnit410RulesWorks.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit410.rules;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.MethodRule;\nimport org.junit.rules.TestName;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\n\n/**\n * This test demonstrates that JUnit 4.10 rules works together with PowerMock\n */\n@RunWith(PowerMockRunner.class)\npublic class AssertThatJUnit410RulesWorks {\n\tprivate static Object BEFORE = new Object();\n\n\tprivate List<Object> objects = new LinkedList<Object>();\n\n\t@Rule\n\tpublic MyRule rule = new MyRule();\n\n\t@Rule\n\tpublic TestName testName = new TestName();\n\n\t@Test\n\tpublic void assertThatJUnit410RulesWorks() throws Exception {\n\t\tassertEquals(1, objects.size());\n\t\tassertSame(BEFORE, objects.get(0));\n\t\tassertEquals(\"assertThatJUnit410RulesWorks\", testName.getMethodName());\n\t}\n\n\tprivate class MyRule implements MethodRule {\n\t\tpublic Statement apply(final Statement base, FrameworkMethod method, Object target) {\n\t\t\treturn new Statement() {\n\t\t\t\t@Override\n\t\t\t\tpublic void evaluate() throws Throwable {\n\t\t\t\t\tobjects.add(BEFORE);\n\t\t\t\t\tbase.evaluate();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/rules/ExceptionHandlingRuleTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit410.rules;\n\nimport org.junit.Before;\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.junit410.rules.impl.SimpleEasyMockJUnitRule;\nimport samples.rule.SimpleThingCreator;\nimport samples.rule.SimpleThingImpl;\nimport samples.rule.ThingToTest;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SimpleThingCreator.class)\npublic class ExceptionHandlingRuleTest {\n\n    @Rule\n    public SimpleEasyMockJUnitRule mocks = new SimpleEasyMockJUnitRule();\n\n    private SimpleThingImpl simpleThingMock = mocks.createMock(SimpleThingImpl.class);\n\n    // object under test\n    private ThingToTest testThing;\n\n    @Before\n    public void setUp() throws Exception {\n        mockStatic(SimpleThingCreator.class);\n        expect(SimpleThingCreator.createSimpleThing()).andReturn(simpleThingMock);\n        replay(SimpleThingCreator.class);\n\n        verify(SimpleThingCreator.class);\n    }\n\n    @Test\n    @Ignore(\"This test SHOULD fail but how do we expect it when verification happens in the rule?\")\n    public void exceptionThrownByRuleFailsTheTest() throws Exception {\n        final String expectedName = \"Smith\";\n        expect(simpleThingMock.getThingName()).andReturn(expectedName);\n        mocks.replay();\n\n        assertEquals(\"wrong name\", expectedName, testThing.getName());\n        // verify will be called by rule\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/rules/NoRuleAssertionErrorTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit410.rules;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.assertTrue;\n\n@RunWith(PowerMockRunner.class)\npublic class NoRuleAssertionErrorTest {\n\n    @Test(expected = AssertionError.class)\n    public void assertionErrorIsThrownOnFailureWhenNoRulesDefined() throws Exception {\n        assertTrue(false);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit410/src/test/java/samples/junit410/rules/impl/SimpleEasyMockJUnitRule.java",
    "content": "package samples.junit410.rules.impl;\n\nimport org.easymock.IMocksControl;\nimport org.junit.rules.MethodRule;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\n\nimport static org.easymock.EasyMock.createControl;\n\n/**\n * A JUnit rule that resets all mocks before each test and verifies the mocks after the test\n */\npublic class SimpleEasyMockJUnitRule implements MethodRule {\n\n    final IMocksControl control;\n    boolean recording = true;\n    public Error caughtError = null;\n\n    /**\n     * Create the rule using the default EasyMock.createControl()\n     */\n    public SimpleEasyMockJUnitRule() {\n        this(createControl());\n    }\n\n    /**\n     * Create the rule using the IMocksControl that you provide\n     * \n     * @param control\n     *            The provided IMocksControl to use for testing\n     */\n    public SimpleEasyMockJUnitRule(IMocksControl control) {\n        this.control = control;\n    }\n\n    public <T> T createMock(Class<T> toMock) {\n        return control.createMock(toMock);\n    }\n\n    public void reset() {\n        recording = true;\n        control.reset();\n    }\n\n    public void replay() {\n        recording = false;\n        control.replay();\n    }\n\n    public void verify() {\n        control.verify();\n    }\n\n    @Override\n    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {\n        return new Statement() {\n\n            @Override\n            public void evaluate() throws Throwable {\n                reset();\n                base.evaluate();\n                if (!recording) {\n                    verify(); // only verify if no exceptions were thrown\n                }\n            }\n        };\n    }\n\n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/TwoObjectsAnnotatedTest.java",
    "content": "package samples.junit412.bug.github755;\n\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.api.easymock.annotation.MockNice;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.newmocking.SomeDependency;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\n@RunWith(PowerMockRunner.class)\npublic class TwoObjectsAnnotatedTest {\n    \n    @Mock\n    private String obj1;\n    \n    @Mock\n    private String obj2;\n    \n    @MockNice\n    private SomeDependency someClass1;\n    \n    @MockNice\n    private SomeDependency someClass2;\n    \n    @Test\n    public void should_create_mock_for_all_fields_annotated_Mock() {\n        assertThat(obj1).isNotNull();\n        assertThat(obj2).isNotNull();\n    }\n    \n    @Test\n    public void should_create_mock_for_all_fields_annotated_MockNice() {\n        assertThat(someClass1).isNotNull();\n        assertThat(someClass2).isNotNull();\n    }\n    \n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/package-info.java",
    "content": "/**\n * @Mock annotation from easymock api does not work for two fields of the same type.\n *\n */\npackage samples.junit412.bug.github755;"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit412.expectnew;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.junit4.expectnew.ExpectNewCases;\nimport samples.newmocking.MyClass;\n\nimport java.io.DataInputStream;\n\n/**\n * Test class to demonstrate new instance mocking using expectNew(..).\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class })\npublic class ExpectNewDemoTest extends ExpectNewCases {\n\n\n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewOfFinalSystemClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit412.expectnew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewOfFinalSystemClassDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.createMock;\nimport static org.powermock.api.easymock.PowerMock.expectNew;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class })\npublic class ExpectNewOfFinalSystemClassTest {\n\n    @Test\n    public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception {\n        String mock = createMock(String.class);\n\n        expectNew(String.class, \"My String\").andReturn(mock);\n        expect(mock.charAt(0)).andReturn('o');\n\n        replayAll();\n        assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar());\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/github668/Github668Test.java",
    "content": "package samples.junit412.github668;\n\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Suite;\n\n\n@RunWith(Suite.class)\n@Suite.SuiteClasses({TwoMockFieldsWithDifferentTypesClass.class, TwoMockFieldsWithSameTypeCase.class})\npublic class Github668Test {\n\n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/github668/IncidentPropertyChangeDAO.java",
    "content": "package samples.junit412.github668;\n\n/**\n *\n */\npublic interface IncidentPropertyChangeDAO {\n    String getIncident();\n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithDifferentTypesClass.java",
    "content": "package samples.junit412.github668;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.api.extension.listener.AnnotationEnabler;\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.Service;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\n\n\n/**\n *\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockListener(AnnotationEnabler.class)\npublic class TwoMockFieldsWithDifferentTypesClass {\n\n    @Mock\n    private IncidentPropertyChangeDAO incidentPropertyChangeDAO;\n\n    @Mock\n    private Service serviceMock;\n\n    @Test\n    public void mockClassShouldInjected() {\n        assertNotNull(incidentPropertyChangeDAO);\n        assertNotNull(serviceMock);\n    }\n    \n    @Test\n    public void shouldBeAbleMockMethodsOfInjected() {\n        expect(incidentPropertyChangeDAO.getIncident()).andReturn(\"value\");\n        expect(serviceMock.getServiceMessage()).andReturn(\"value\");\n\n        replayAll(incidentPropertyChangeDAO, serviceMock);\n\n        assertEquals(\"value\", incidentPropertyChangeDAO.getIncident());\n        assertEquals(\"value\", serviceMock.getServiceMessage());\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithSameTypeCase.java",
    "content": "package samples.junit412.github668;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.api.extension.listener.AnnotationEnabler;\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\n\n\n/**\n *\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockListener(AnnotationEnabler.class)\npublic class TwoMockFieldsWithSameTypeCase {\n\n    @Mock(fieldName = \"incidentPropertyChangeDAO\")\n    private IncidentPropertyChangeDAO incidentPropertyChangeDAO;\n\n    @Mock(fieldName = \"propertyChangeDAO\")\n    private IncidentPropertyChangeDAO propertyChangeDAO;\n\n    @Test\n    public void mockClassShouldInjected() {\n        assertNotNull(incidentPropertyChangeDAO);\n        assertNotNull(propertyChangeDAO);\n    }\n    \n    @Test\n    public void shouldBeAbleMockMethodsOfInjected() {\n        expect(incidentPropertyChangeDAO.getIncident()).andReturn(\"value\");\n        expect(propertyChangeDAO.getIncident()).andReturn(\"value1\");\n\n        replayAll(incidentPropertyChangeDAO,propertyChangeDAO);\n\n        assertEquals(\"value\", incidentPropertyChangeDAO.getIncident());\n        assertEquals(\"value1\", propertyChangeDAO.getIncident());\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit412/src/test/java/samples/junit412/github668/package-info.java",
    "content": "/**\n * \\@Mock fields are not injected anymore (1.6.5 regression)\n * https://github.com/jayway/powermock/issues/668\n */\npackage samples.junit412.github668;"
  },
  {
    "path": "tests/easymock/junit45/src/main/java/demo/org/powermock/modules/test/junit45/failure/MyClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage demo.org.powermock.modules.test.junit45.failure;\n\npublic class MyClass {\n\n\tpublic int sum(int a, int b) throws MyException {\n\t\tif (MyUtils.isValid(a))\n\t\t\tthrow new MyException();\n\t\telse\n\t\t\treturn a + b;\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit45/src/main/java/demo/org/powermock/modules/test/junit45/failure/MyException.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage demo.org.powermock.modules.test.junit45.failure;\n\npublic class MyException extends Exception {\n\tprivate static final long serialVersionUID = -222072316863858540L;\n\n}\n"
  },
  {
    "path": "tests/easymock/junit45/src/main/java/demo/org/powermock/modules/test/junit45/failure/MyUtils.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage demo.org.powermock.modules.test.junit45.failure;\n\npublic class MyUtils {\n\n\tpublic static boolean isValid(int a) {\n\t\treturn a > 10;\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit45/src/test/java/demo/org/powermock/modules/test/junit45/failure/AssertThatJUnit45FailuresWorkTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage demo.org.powermock.modules.test.junit45.failure;\n\nimport org.easymock.EasyMock;\nimport org.junit.Test;\nimport org.junit.internal.AssumptionViolatedException;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.PowerMock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl;\n\nimport static org.junit.Assert.assertTrue;\n\n/**\n * This test asserts that JUnit 4.5 failures works as expected. Previously the\n * {@link PowerMockJUnit44RunnerDelegateImpl} got a {@link NoClassDefFoundError}\n * when trying to load JUnit 4.4's {@link AssumptionViolatedException} which has\n * been moved in JUnit 4.5. Thanks to Manuel Fern�ndez S�nchez de la Blanca for\n * creating this test case to prove the issue.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(MyUtils.class)\npublic class AssertThatJUnit45FailuresWorkTest {\n\n\t@Test(expected = AssumptionViolatedException.class)\n\tpublic void testAssumptionViolatedException() throws MyException {\n\t\tthrow new AssumptionViolatedException(\"Not true!\");\n\t}\n\n\t@Test(expected = MyException.class)\n\tpublic void testSum() throws MyException {\n\t\tPowerMock.mockStatic(MyUtils.class);\n\t\tEasyMock.expect(MyUtils.isValid(1)).andReturn(true);\n\t\tPowerMock.replay(MyUtils.class);\n\n\t\tMyClass myclass = new MyClass();\n\t\tint result = myclass.sum(1, 2);\n\t\tPowerMock.verify(MyUtils.class);\n\n\t\tassertTrue(result == 3);\n\t}\n\n\t@Test(expected = MyException.class)\n\tpublic void testSum2() throws MyException {\n\t\tMyClass myclass = new MyClass();\n\t\tmyclass.sum(100, 2);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit47/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.testlisteners.FieldDefaulter;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with multiple test\n * listeners for JUnit 4.7.\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\n@PowerMockListener( { FieldDefaulter.class })\npublic class FinalDemoWithAnnotationInjectionAndFieldDefaulterTest {\n\n\t@SuppressWarnings(\"unused\")\n\t// Asserts that the FieldDefaulter handles primitive types.\n\tprivate int intType = 6;\n\n\t@Mock\n\tprivate FinalDemo tested;\n\n\t@Test\n\tpublic void testSay() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.say(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testSayFinalNative() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.sayFinalNative(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.sayFinalNative(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.sayFinalNative(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/junit47/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.expectnew;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\n\nimport java.io.DataInputStream;\n\n/**\n * Test class to demonstrate new instance mocking using expectNew(..).\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class })\npublic class ExpectNewDemoTest extends ExpectNewCases {\n\n\n}\n"
  },
  {
    "path": "tests/easymock/junit47/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.expectnew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewOfFinalSystemClassDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class })\npublic class ExpectNewOfFinalSystemClassTest {\n\n    @Test\n    public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception {\n        String mock = createMock(String.class);\n\n        expectNew(String.class, \"My String\").andReturn(mock);\n        expect(mock.charAt(0)).andReturn('o');\n\n        replayAll();\n        assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar());\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit47/src/test/java/samples/junit4/rules/AssertThatJUnit47RulesWorks.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.rules;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.MethodRule;\nimport org.junit.rules.TestName;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\n\n/**\n * This test demonstrates that JUnit 4.7 rules works together with PowerMock\n */\n@RunWith(PowerMockRunner.class)\npublic class AssertThatJUnit47RulesWorks {\n\tprivate static Object BEFORE = new Object();\n\n\tprivate List<Object> objects = new LinkedList<Object>();\n\n\t@Rule\n\tpublic MyRule rule = new MyRule();\n\n\t@Rule\n\tpublic TestName testName = new TestName();\n\n\t@Test\n\tpublic void assertThatJUnit47RulesWorks() throws Exception {\n\t\tassertEquals(1, objects.size());\n\t\tassertSame(BEFORE, objects.get(0));\n\t\tassertEquals(\"assertThatJUnit47RulesWorks\", testName.getMethodName());\n\t}\n\n\tprivate class MyRule implements MethodRule {\n\t\t@Override\n\t\tpublic Statement apply(final Statement base, FrameworkMethod method, Object target) {\n\t\t\treturn new Statement() {\n\t\t\t\t@Override\n\t\t\t\tpublic void evaluate() throws Throwable {\n\t\t\t\t\tobjects.add(BEFORE);\n\t\t\t\t\tbase.evaluate();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit47/src/test/java/samples/junit4/rules/NoRuleAssertionErrorTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.rules;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.assertTrue;\n\n@RunWith(PowerMockRunner.class)\npublic class NoRuleAssertionErrorTest {\n\n    @Test(expected = AssertionError.class)\n    public void assertionErrorIsThrownOnFailureWhenNoRulesDefined() throws Exception {\n        assertTrue(false);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit47/src/test/java/samples/junit4/rules/RuleOrderTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.rules;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TemporaryFolder;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.hamcrest.CoreMatchers.*;\nimport static org.junit.Assert.assertThat;\n\n@RunWith(PowerMockRunner.class)\npublic class RuleOrderTest {\n\n    private static final String EMPTY_STRING = \"\";\n\n    @Rule\n    public TemporaryFolder folder = new TemporaryFolder();\n\n    private String temporaryFileName = EMPTY_STRING;\n\n    @Before\n    public void setup() throws Exception {\n        temporaryFileName = folder.newFile(\"tempFile\").getPath();\n    }\n\n    @Test\n    public void rulesAreExecutedBeforeSetupMethods() throws Exception {\n        assertThat(temporaryFileName, not(nullValue()));\n        assertThat(temporaryFileName, not(equalTo(EMPTY_STRING)));\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit47/src/test/java/samples/junit4/rules/ThrowingRuleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit4.rules;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n/**\n * Asserts that expected expectation rules also works with the PowerMock JUnit\n * 4.7 runner. Asserts that <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=179\">issue 179</a>\n * has been resolved. Thanks to Andrei Ivanov for finding this bug.\n */\n@RunWith(PowerMockRunner.class)\npublic class ThrowingRuleTest {\n    @Rule\n    public ExpectedException thrown = ExpectedException.none();\n\n    @Test\n    public void throwsNullPointerException() {\n        thrown.expect(RuntimeException.class);\n        throw new RuntimeException();\n    }\n\n    @Test\n    public void throwsNullPointerExceptionWithMessage() {\n        thrown.expect(NullPointerException.class);\n        thrown.expectMessage(\"What happened?\");\n        throw new NullPointerException(\"What happened?\");\n    }\n\n    @Test(expected = NullPointerException.class)\n    public void unexpectAssertionErrorFailsTestCorrectly() {\n        throw new NullPointerException(\"What happened?\");\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/expectnew/ExpectNewDemoTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit48.expectnew;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.junit4.expectnew.ExpectNewCases;\nimport samples.newmocking.MyClass;\n\nimport java.io.DataInputStream;\n\n/**\n * Test class to demonstrate new instance mocking using expectNew(..).\n * \n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class })\npublic class ExpectNewDemoTest extends ExpectNewCases{\n\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/expectnew/ExpectNewOfFinalSystemClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit48.expectnew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewOfFinalSystemClassDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class })\npublic class ExpectNewOfFinalSystemClassTest {\n\n    @Test\n    public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception {\n        String mock = createMock(String.class);\n\n        expectNew(String.class, \"My String\").andReturn(mock);\n        expect(mock.charAt(0)).andReturn('o');\n\n        replayAll();\n        assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar());\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/rules/AssertThatJUnit48RulesWorks.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit48.rules;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.MethodRule;\nimport org.junit.rules.TestName;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\n\n/**\n * This test demonstrates that JUnit 4.7 rules works together with PowerMock\n */\n@RunWith(PowerMockRunner.class)\npublic class AssertThatJUnit48RulesWorks {\n\tprivate static Object BEFORE = new Object();\n\n\tprivate List<Object> objects = new LinkedList<Object>();\n\n\t@Rule\n\tpublic MyRule rule = new MyRule();\n\n\t@Rule\n\tpublic TestName testName = new TestName();\n\n\t@Test\n\tpublic void assertThatJUnit47RulesWorks() throws Exception {\n\t\tassertEquals(1, objects.size());\n\t\tassertSame(BEFORE, objects.get(0));\n\t\tassertEquals(\"assertThatJUnit47RulesWorks\", testName.getMethodName());\n\t}\n\n\tprivate class MyRule implements MethodRule {\n\t\t@Override\n\t\tpublic Statement apply(final Statement base, FrameworkMethod method, Object target) {\n\t\t\treturn new Statement() {\n\t\t\t\t@Override\n\t\t\t\tpublic void evaluate() throws Throwable {\n\t\t\t\t\tobjects.add(BEFORE);\n\t\t\t\t\tbase.evaluate();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/rules/ExceptionHandlingRuleTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.junit48.rules;\n\nimport org.junit.Before;\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.junit48.rules.impl.SimpleEasyMockJUnitRule;\nimport samples.rule.SimpleThingCreator;\nimport samples.rule.SimpleThingImpl;\nimport samples.rule.ThingToTest;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SimpleThingCreator.class)\npublic class ExceptionHandlingRuleTest {\n\n    @Rule\n    public SimpleEasyMockJUnitRule mocks = new SimpleEasyMockJUnitRule();\n\n    private SimpleThingImpl simpleThingMock = mocks.createMock(SimpleThingImpl.class);\n\n    // object under test\n    private ThingToTest testThing;\n\n    @Before\n    public void setUp() throws Exception {\n        mockStatic(SimpleThingCreator.class);\n        expect(SimpleThingCreator.createSimpleThing()).andReturn(simpleThingMock);\n        replay(SimpleThingCreator.class);\n\n        verify(SimpleThingCreator.class);\n    }\n\n    @Test\n    @Ignore(\"This test SHOULD fail but how do we expect it when verification happens in the rule?\")\n    public void exceptionThrownByRuleFailsTheTest() throws Exception {\n        final String expectedName = \"Smith\";\n        expect(simpleThingMock.getThingName()).andReturn(expectedName);\n        mocks.replay();\n\n        assertEquals(\"wrong name\", expectedName, testThing.getName());\n        // verify will be called by rule\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/rules/NoRuleAssertionErrorTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit48.rules;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.assertTrue;\n\n@RunWith(PowerMockRunner.class)\npublic class NoRuleAssertionErrorTest {\n\n    @Test(expected = AssertionError.class)\n    public void assertionErrorIsThrownOnFailureWhenNoRulesDefined() throws Exception {\n        assertTrue(false);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/rules/RuleOrderTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit48.rules;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TemporaryFolder;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.hamcrest.CoreMatchers.*;\nimport static org.junit.Assert.assertThat;\n\n@RunWith(PowerMockRunner.class)\npublic class RuleOrderTest {\n\n    private static final String EMPTY_STRING = \"\";\n\n    @Rule\n    public TemporaryFolder folder = new TemporaryFolder();\n\n    private String temporaryFileName = EMPTY_STRING;\n\n    @Before\n    public void setup() throws Exception {\n        temporaryFileName = folder.newFile(\"tempFile\").getPath();\n    }\n\n    @Test\n    public void rulesAreExecutedBeforeSetupMethods() throws Exception {\n        assertThat(temporaryFileName, not(nullValue()));\n        assertThat(temporaryFileName, not(equalTo(EMPTY_STRING)));\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/rules/ThrowingRuleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.junit48.rules;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n/**\n * Asserts that expected expectation rules also works with the PowerMock JUnit\n * 4.7 runner. Asserts that <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=179\">issue 179</a>\n * has been resolved. Thanks to Andrei Ivanov for finding this bug.\n */\n@RunWith(PowerMockRunner.class)\npublic class ThrowingRuleTest {\n    @Rule\n    public ExpectedException thrown = ExpectedException.none();\n\n    @Test\n    public void throwsNullPointerException() {\n        thrown.expect(RuntimeException.class);\n        throw new RuntimeException();\n    }\n\n    @Test\n    public void throwsNullPointerExceptionWithMessage() {\n        thrown.expect(NullPointerException.class);\n        thrown.expectMessage(\"What happened?\");\n        throw new NullPointerException(\"What happened?\");\n    }\n\n    @Test(expected = NullPointerException.class)\n    public void unexpectAssertionErrorFailsTestCorrectly() {\n        throw new NullPointerException(\"What happened?\");\n    }\n}\n"
  },
  {
    "path": "tests/easymock/junit48/src/test/java/samples/junit48/rules/impl/SimpleEasyMockJUnitRule.java",
    "content": "package samples.junit48.rules.impl;\n\nimport org.easymock.IMocksControl;\nimport org.junit.rules.MethodRule;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\n\nimport static org.easymock.EasyMock.createControl;\n\n/**\n * A JUnit rule that resets all mocks before each test and verifies the mocks after the test\n */\npublic class SimpleEasyMockJUnitRule implements MethodRule {\n\n    final IMocksControl control;\n    boolean recording = true;\n    public Error caughtError = null;\n\n    /**\n     * Create the rule using the default EasyMock.createControl()\n     */\n    public SimpleEasyMockJUnitRule() {\n        this(createControl());\n    }\n\n    /**\n     * Create the rule using the IMocksControl that you provide\n     * \n     * @param control\n     *            The provided IMocksControl to use for testing\n     */\n    public SimpleEasyMockJUnitRule(IMocksControl control) {\n        this.control = control;\n    }\n\n    public <T> T createMock(Class<T> toMock) {\n        return control.createMock(toMock);\n    }\n\n    public void reset() {\n        recording = true;\n        control.reset();\n    }\n\n    public void replay() {\n        recording = false;\n        control.replay();\n    }\n\n    public void verify() {\n        control.verify();\n    }\n\n    @Override\n    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {\n        return new Statement() {\n\n            @Override\n            public void evaluate() throws Throwable {\n                reset();\n                base.evaluate();\n                if (!recording) {\n                    verify(); // only verify if no exceptions were thrown\n                }\n            }\n        };\n    }\n\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoTest.java",
    "content": "package samples.testng;\n\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n/**\n * Verifies that PowerMock test listeners works correctly in TestNG.\n */\n@PrepareForTest\npublic class AnnotationDemoTest {\n\n    @Mock\n    private Service serviceMock;\n\n    @Test\n    public void assertInjectionWorked() throws Exception {\n        AnnotationDemo tested = new AnnotationDemo(serviceMock);\n        final String expected = \"mock\";\n        expect(serviceMock.getServiceMessage()).andReturn(expected);\n\n        replayAll();\n\n        Assert.assertEquals(expected, tested.getServiceMessage());\n\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoWithBeforeMethodTest.java",
    "content": "package samples.testng;\n\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n/**\n * Verifies that PowerMock test listeners works correctly with before methods in\n * TestNG.\n */\npublic class AnnotationDemoWithBeforeMethodTest {\n\n\t@Mock\n\tprivate Service serviceMock;\n\n\tprivate AnnotationDemo tested;\n\n\t@BeforeMethod\n\tpublic void setup() {\n\t\ttested = new AnnotationDemo(serviceMock);\n\t}\n\n\t@Test\n    @PrepareForTest\n\tpublic void assertInjectionWorked() throws Exception {\n\t\tfinal String expected = \"mock\";\n\t\texpect(serviceMock.getServiceMessage()).andReturn(expected);\n\n\t\treplayAll();\n\n\t\tAssert.assertEquals(expected, tested.getServiceMessage());\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/DocumentBuilderFactoryTest.java",
    "content": "package samples.testng;\n\nimport org.testng.annotations.Test;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\n\npublic class DocumentBuilderFactoryTest {\n\n    @Test\n    public void classesNotAnnotatedWithPrepareForTestAreNotLoadedByByPowerMockCl() throws Exception {\n        DocumentBuilderFactory.newInstance();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/FinalTest.java",
    "content": "package samples.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.annotations.Test;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\nimport static org.testng.Assert.assertEquals;\n\n@PrepareForTest(FinalDemo.class)\npublic class FinalTest extends PowerMockTestCase {\n\n    @Test\n    public void mockingFinalClassesAndMethodsWorkWithTestNGAndEasyMock() throws Exception {\n        final FinalDemo finalDemo = createMock(FinalDemo.class);\n\n        expect(finalDemo.say(\"something\")).andReturn(\"something else\");\n\n        replayAll();\n\n        final String actual = finalDemo.say(\"something\");\n\n        verifyAll();\n\n        assertEquals(\"something else\", actual);\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/MockStaticExtendsPowerMockTestCaseTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n * \n * @author Johan Haleby\n * @author Jan Kronquist\n */\n@PrepareForTest( { StaticService.class, StaticHelper.class })\npublic class MockStaticExtendsPowerMockTestCaseTest extends PowerMockTestCase {\n\n    @Test\n    public void testMockStatic() throws Exception {\n        mockStatic(StaticService.class);\n        String expected = \"Hello altered World\";\n        expect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n        replay(StaticService.class);\n\n        String actual = StaticService.say(\"hello\");\n\n        verify(StaticService.class);\n        Assert.assertEquals(expected, actual);\n\n        // Singleton still be mocked by now.\n        try {\n            StaticService.say(\"world\");\n            Assert.fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            Assert.assertEquals(\"\\n  Unexpected method call StaticService.say(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testMockStaticFinal() throws Exception {\n        mockStatic(StaticService.class);\n        String expected = \"Hello altered World\";\n        expect(StaticService.sayFinal(\"hello\")).andReturn(\"Hello altered World\");\n        replay(StaticService.class);\n\n        String actual = StaticService.sayFinal(\"hello\");\n\n        verify(StaticService.class);\n        Assert.assertEquals(expected, actual);\n\n        // Singleton still be mocked by now.\n        try {\n            StaticService.sayFinal(\"world\");\n            Assert.fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            Assert.assertEquals(\"\\n  Unexpected method call StaticService.sayFinal(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/MockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.mockStatic;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n * \n * @author Johan Haleby\n * @author Jan Kronquist\n */\n@PrepareForTest( { StaticService.class, StaticHelper.class })\npublic class MockStaticTest {\n\n\t@Test\n\tpublic void testMockStatic() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.say(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tAssert.assertEquals(expected, actual);\n\n\t}\n\n\t@Test\n\tpublic void testMockStaticFinal() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayFinal(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayFinal(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tAssert.assertEquals(expected, actual);\n\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/NotAnnotatedWithPrepareForTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.testng;\n\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertFalse;\n\npublic class NotAnnotatedWithPrepareForTest {\n\n    @Test\n\tpublic void classesNotAnnotatedWithPrepareForTestAreNotLoadedByPowerMockClassloader() throws Exception {\n        final ClassLoader classLoader = getClass().getClassLoader();\n        assertFalse(MockClassLoader.class.getName().equals(classLoader.getClass().getName()));\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/PartialMockingWithBeforeClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\nimport samples.privateandfinal.PrivateFinal;\n\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.powermock.api.easymock.PowerMock.createPartialMock;\nimport static org.powermock.api.easymock.PowerMock.expectPrivate;\n\n/**\n * Test class to demonstrate private+final method mocking.\n */\n@PrepareForTest(PrivateFinal.class)\npublic class PartialMockingWithBeforeClassTest extends PowerMockTestCase {\n\tprivate PrivateFinal tested;\n\n\t@BeforeClass\n\tpublic void setup() {\n\t\ttested = createPartialMock(PrivateFinal.class, \"sayIt\");\n\t}\n\n\t@Test\n\tpublic void partialMockingWithMockCreatedInBeforeClassMethod() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\t\texpectPrivate(tested, \"sayIt\", \"name\").andReturn(expected);\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"name\");\n\n\t\tverify(tested);\n\t\tAssert.assertEquals(expected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/PrivateFinalTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.privateandfinal.PrivateFinal;\n\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.powermock.api.easymock.PowerMock.createPartialMock;\nimport static org.powermock.api.easymock.PowerMock.expectPrivate;\n\n/**\n * Test class to demonstrate private+final method mocking.\n */\n@PrepareForTest(PrivateFinal.class)\npublic class PrivateFinalTest {\n\n  @Test\n  public void testSay() throws Exception {\n    PrivateFinal tested = createPartialMock(PrivateFinal.class, \"sayIt\");\n    String expected = \"Hello altered World\";\n    expectPrivate(tested, \"sayIt\", \"name\").andReturn(expected);\n    replay(tested);\n\n    String actual = tested.say(\"name\");\n\n    verify(tested);\n    Assert.assertEquals(expected, actual);\n  }\n\n  @Test\n  public void testMultiMock() throws Exception {\n    PrivateFinal tested1 = createPartialMock(PrivateFinal.class, \"sayIt\");\n    String expected1 = \"Hello altered World\";\n    expectPrivate(tested1, \"sayIt\", \"name\").andReturn(expected1);\n    replay(tested1);\n    PrivateFinal tested2 = createPartialMock(PrivateFinal.class, \"sayIt\");\n    String expected2 = \"Hello qweqweqwe\";\n    expectPrivate(tested2, \"sayIt\", \"name\").andReturn(expected2);\n    replay(tested2);\n\n    String actual1 = tested1.say(\"name\");\n    verify(tested1);\n    Assert.assertEquals(expected1, actual1);\n    String actual2 = tested2.say(\"name\");\n    verify(tested2);\n    Assert.assertEquals(expected2, actual2);\n  }\n\n  \n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/SampleServletTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockObjectFactory;\nimport org.testng.IObjectFactory;\nimport org.testng.annotations.ObjectFactory;\nimport org.testng.annotations.Test;\nimport samples.servletmocking.SampleServlet;\n\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.PrintWriter;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@PrepareForTest(SampleServlet.class)\npublic class SampleServletTest {\n\n    @Test\n    public void doGet() throws Exception {\n        SampleServlet servlet = new SampleServlet();\n\n        HttpServletResponse response = createMock(HttpServletResponse.class);\n        PrintWriter writer = createMock(PrintWriter.class);\n\n        expect(response.getWriter()).andReturn(writer);\n        writer.write(\"out\");\n\n        replay(response, writer);\n\n        servlet.doGet(null, response);\n\n        verify(response, writer);\n    }\n\n    @ObjectFactory\n    public IObjectFactory getObjectFactory() {\n        return new PowerMockObjectFactory();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/StaticInitializerExampleTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng;\n\nimport org.testng.annotations.Test;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.reflect.Whitebox;\nimport samples.staticinitializer.StaticInitializerExample;\n\nimport java.util.HashSet;\n\nimport static org.testng.Assert.*;\nimport org.powermock.modules.testng.PowerMockTestCase;\n\n@SuppressStaticInitializationFor(\"samples.staticinitializer.StaticInitializerExample\")\npublic class StaticInitializerExampleTest extends PowerMockTestCase {\n\n\t@Test\n\tpublic void testSupressStaticInitializer() throws Exception {\n\t\tassertNull(StaticInitializerExample.getMySet(), \"Should be null because the static initializer should be suppressed\");\n\t}\n\n\t@Test\n\tpublic void testSupressStaticInitializerAndSetFinalField() throws Exception {\n\t\tassertNull(StaticInitializerExample.getMySet(), \"Should be null because the static initializer should be suppressed\");\n\t\tfinal HashSet<String> hashSet = new HashSet<String>();\n\t\tWhitebox.setInternalState(StaticInitializerExample.class, \"mySet\", hashSet);\n\t\tassertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, \"mySet\"));\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng/src/test/java/samples/testng/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.testng.annotations.Test;\nimport samples.system.SystemClassUser;\n\nimport java.net.InetAddress;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.easymock.EasyMock.anyLong;\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\nimport static org.testng.Assert.assertSame;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.AssertJUnit.assertEquals;\n\n/**\n * Demonstrates PowerMock's ability to mock non-final and final system classes.\n * To mock a system class you need to prepare the calling class for testing.\n * I.e. let's say you're testing class A which interacts with URLEncoder then\n * you would do:\n *\n * <pre>\n *\n * &#064;PrepareForTest({A.class})\n *\n * </pre>\n */\n@PrepareForTest( { SystemClassUser.class })\npublic class SystemClassUserTest {\n\n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n\n        expect(URLEncoder.encode(\"string\", \"enc\")).andReturn(\"something\");\n        replayAll();\n\n        assertEquals(\"something\", new SystemClassUser().performEncode());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n\n        Runtime runtimeMock = createMock(Runtime.class);\n        Process processMock = createMock(Process.class);\n\n        expect(Runtime.getRuntime()).andReturn(runtimeMock);\n        expect(runtimeMock.exec(\"command\")).andReturn(processMock);\n\n        replayAll();\n\n        assertSame(processMock, new SystemClassUser().executeCommand());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n\n        expect(System.getProperty(\"property\")).andReturn(\"my property\");\n\n        replayAll();\n\n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStaticPartial(System.class, \"nanoTime\");\n\n        expect(System.nanoTime()).andReturn(2L);\n\n        replayAll();\n\n        new SystemClassUser().doMoreComplicatedStuff();\n\n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n\n        Collections.shuffle(list);\n        expectLastCall().once();\n\n        replayAll();\n\n        new SystemClassUser().shuffleCollection(list);\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        mockStaticPartial(System.class, \"getProperty\");\n\n        expect(System.getProperty(\"property\")).andReturn(\"my property\");\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n\n        expect(String.format(string, args)).andReturn(returnValue);\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingStaticVoidMethodWorks() throws Exception {\n        mockStatic(Thread.class);\n\n        Thread.sleep(anyLong());\n        expectLastCall().once();\n\n        replayAll();\n\n        long startTime = System.currentTimeMillis();\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.threadSleep();\n        long endTime = System.currentTimeMillis();\n        assertTrue(endTime - startTime < 5000);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingInstanceMethodOfFinalSystemClassWorks() throws Exception {\n        URL url = createMock(URL.class);\n        URLConnection urlConnection = createMock(URLConnection.class);\n\n        expect(url.openConnection()).andStubReturn(urlConnection);\n\n        replayAll();\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertSame(urlConnection, systemClassUser.useURL(url));\n        verifyAll();\n    }\n\n    @Test\n    public void mockingURLWorks() throws Exception {\n        URL url = createMock(URL.class);\n        URLConnection urlConnectionMock = createMock(URLConnection.class);\n\n        expect(url.openConnection()).andReturn(urlConnectionMock);\n\n        replayAll();\n\n        assertSame(url.openConnection(), urlConnectionMock);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingInetAddressWorks() throws Exception {\n        final InetAddress mock = createMock(InetAddress.class);\n        mockStatic(InetAddress.class);\n\n        expect(InetAddress.getLocalHost()).andReturn(mock);\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertSame(mock, systemClassUser.getLocalHost());\n\n        verifyAll();\n    }\n}"
  },
  {
    "path": "tests/easymock/testng/suite.xml",
    "content": "<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name=\"EasyMock TestNG\" verbose=\"10\" object-factory=\"org.powermock.modules.testng.PowerMockObjectFactory\">\n    <test name=\"General\">\n        <classes>\n            <class name=\"samples.testng.AnnotationDemoTest\"/>\n            <class name=\"samples.testng.AnnotationDemoWithBeforeMethodTest\"/>\n            <class name=\"samples.testng.DocumentBuilderFactoryTest\" />\n            <class name=\"samples.testng.FinalTest\" />\n            <class name=\"samples.testng.MockStaticExtendsPowerMockTestCaseTest\"/>\n            <class name=\"samples.testng.MockStaticTest\"/>\n            <class name=\"samples.testng.NotAnnotatedWithPrepareForTest\"/>\n            <class name=\"samples.testng.PartialMockingWithBeforeClassTest\"/>\n            <class name=\"samples.testng.PrivateFinalTest\"/>\n            <class name=\"samples.testng.SampleServletTest\" />\n            <class name=\"samples.testng.SystemClassUserTest\" />\n        </classes>\n    </test>\n</suite>"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoTest.java",
    "content": "package samples.testng.agent;\n\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n/**\n * Verifies that PowerMock test listeners works correctly in TestNG.\n */\n@PrepareForTest\npublic class AnnotationDemoTest extends PowerMockTestCase {\n\n    @Mock\n    private Service serviceMock;\n\n    @Test\n    public void assertInjectionWorked() throws Exception {\n        AnnotationDemo tested = new AnnotationDemo(serviceMock);\n        final String expected = \"mock\";\n        expect(serviceMock.getServiceMessage()).andReturn(expected);\n\n        replayAll();\n\n        Assert.assertEquals(expected, tested.getServiceMessage());\n\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoWithBeforeMethodTest.java",
    "content": "package samples.testng.agent;\n\nimport org.powermock.api.easymock.annotation.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n/**\n * Verifies that PowerMock test listeners works correctly with before methods in\n * TestNG.\n */\npublic class AnnotationDemoWithBeforeMethodTest extends PowerMockTestCase {\n\n\t@Mock\n\tprivate Service serviceMock;\n\n\tprivate AnnotationDemo tested;\n\n\t@BeforeMethod\n\tpublic void setup() {\n\t\ttested = new AnnotationDemo(serviceMock);\n\t}\n\n\t@Test\n    @PrepareForTest\n\tpublic void assertInjectionWorked() throws Exception {\n\t\tfinal String expected = \"mock\";\n\t\texpect(serviceMock.getServiceMessage()).andReturn(expected);\n\n\t\treplayAll();\n\n\t\tAssert.assertEquals(expected, tested.getServiceMessage());\n\n\t\tverifyAll();\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/FinalDemoTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.AssertJUnit;\nimport org.testng.annotations.Test;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\nimport static org.testng.Assert.fail;\nimport static org.testng.AssertJUnit.assertEquals;\n\n/**\n * Test class to demonstrate non-static final mocking.\n *\n */\n@PrepareForTest(FinalDemo.class)\npublic class FinalDemoTest extends PowerMockTestCase {\n\n\t@Test\n\tpublic void testSay() throws Exception {\n\t\tFinalDemo tested = createMock(FinalDemo.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"hello\");\n\n\t\tverify(tested);\n\t\tAssertJUnit.assertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.say(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\n\t}\n\n\t@Test\n\tpublic void testSayFinalNative() throws Exception {\n\t\tFinalDemo tested = createMock(FinalDemo.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(tested.sayFinalNative(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(tested);\n\n\t\tString actual = tested.sayFinalNative(\"hello\");\n\n\t\tverify(tested);\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\ttested.sayFinalNative(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertEquals(\"\\n  Unexpected method call FinalDemo.sayFinalNative(\\\"world\\\"):\", e.getMessage());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticExtendsPowerMockTestCaseTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n *\n * @author Johan Haleby\n * @author Jan Kronquist\n */\n@PrepareForTest( { StaticService.class, StaticHelper.class })\npublic class MockStaticExtendsPowerMockTestCaseTest extends PowerMockTestCase {\n\n    @Test\n    public void testMockStatic() throws Exception {\n        mockStatic(StaticService.class);\n        String expected = \"Hello altered World\";\n        expect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n        replay(StaticService.class);\n\n        String actual = StaticService.say(\"hello\");\n\n        verify(StaticService.class);\n        Assert.assertEquals(expected, actual);\n\n        // Singleton still be mocked by now.\n        try {\n            StaticService.say(\"world\");\n            Assert.fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            Assert.assertEquals(\"\\n  Unexpected method call StaticService.say(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testMockStaticFinal() throws Exception {\n        mockStatic(StaticService.class);\n        String expected = \"Hello altered World\";\n        expect(StaticService.sayFinal(\"hello\")).andReturn(\"Hello altered World\");\n        replay(StaticService.class);\n\n        String actual = StaticService.sayFinal(\"hello\");\n\n        verify(StaticService.class);\n        Assert.assertEquals(expected, actual);\n\n        // Singleton still be mocked by now.\n        try {\n            StaticService.sayFinal(\"world\");\n            Assert.fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            Assert.assertEquals(\"\\n  Unexpected method call StaticService.sayFinal(\\\"world\\\"):\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.mockStatic;\nimport static org.powermock.api.easymock.PowerMock.replay;\nimport static org.powermock.api.easymock.PowerMock.verify;\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n * \n * @author Johan Haleby\n * @author Jan Kronquist\n */\n@PrepareForTest( { StaticService.class, StaticHelper.class })\npublic class MockStaticTest extends PowerMockTestCase {\n\n\t@Test\n\tpublic void testMockStatic() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.say(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.say(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tAssert.assertEquals(expected, actual);\n\n\t}\n\n\t@Test\n\tpublic void testMockStaticFinal() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tString expected = \"Hello altered World\";\n\t\texpect(StaticService.sayFinal(\"hello\")).andReturn(\"Hello altered World\");\n\t\treplay(StaticService.class);\n\n\t\tString actual = StaticService.sayFinal(\"hello\");\n\n\t\tverify(StaticService.class);\n\t\tAssert.assertEquals(expected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/NotAnnotatedWithPrepareForTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertFalse;\n\npublic class NotAnnotatedWithPrepareForTest {\n\n    @Test\n\tpublic void classesNotAnnotatedWithPrepareForTestAreNotLoadedByPowerMockClassloader() throws Exception {\n        final ClassLoader classLoader = getClass().getClassLoader();\n        assertFalse(MockClassLoader.class.getName().equals(classLoader.getClass().getName()));\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/PartialMockingWithBeforeClassTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\nimport samples.privateandfinal.PrivateFinal;\n\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.powermock.api.easymock.PowerMock.createPartialMock;\nimport static org.powermock.api.easymock.PowerMock.expectPrivate;\n\n/**\n * Test class to demonstrate private+final method mocking.\n */\n@PrepareForTest(PrivateFinal.class)\npublic class PartialMockingWithBeforeClassTest extends PowerMockTestCase {\n\tprivate PrivateFinal tested;\n\n\t@BeforeClass\n\tpublic void setup() {\n\t\ttested = createPartialMock(PrivateFinal.class, \"sayIt\");\n\t}\n\n\t@Test\n\tpublic void partialMockingWithMockCreatedInBeforeClassMethod() throws Exception {\n\t\tString expected = \"Hello altered World\";\n\t\texpectPrivate(tested, \"sayIt\", \"name\").andReturn(expected);\n\t\treplay(tested);\n\n\t\tString actual = tested.say(\"name\");\n\n\t\tverify(tested);\n\t\tAssert.assertEquals(expected, actual);\n\t}\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/PrivateFinalTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport samples.privateandfinal.PrivateFinal;\n\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.powermock.api.easymock.PowerMock.createPartialMock;\nimport static org.powermock.api.easymock.PowerMock.expectPrivate;\n\n/**\n * Test class to demonstrate private+final method mocking.\n */\n@PrepareForTest(PrivateFinal.class)\npublic class PrivateFinalTest {\n\n  @Test\n  public void testSay() throws Exception {\n    PrivateFinal tested = createPartialMock(PrivateFinal.class, \"sayIt\");\n    String expected = \"Hello altered World\";\n    expectPrivate(tested, \"sayIt\", \"name\").andReturn(expected);\n    replay(tested);\n\n    String actual = tested.say(\"name\");\n\n    verify(tested);\n    Assert.assertEquals(expected, actual);\n  }\n\n  @Test\n  public void testMultiMock() throws Exception {\n    PrivateFinal tested1 = createPartialMock(PrivateFinal.class, \"sayIt\");\n    String expected1 = \"Hello altered World\";\n    expectPrivate(tested1, \"sayIt\", \"name\").andReturn(expected1);\n    replay(tested1);\n    PrivateFinal tested2 = createPartialMock(PrivateFinal.class, \"sayIt\");\n    String expected2 = \"Hello qweqweqwe\";\n    expectPrivate(tested2, \"sayIt\", \"name\").andReturn(expected2);\n    replay(tested2);\n\n    String actual1 = tested1.say(\"name\");\n    verify(tested1);\n    Assert.assertEquals(expected1, actual1);\n    String actual2 = tested2.say(\"name\");\n    verify(tested2);\n    Assert.assertEquals(expected2, actual2);\n  }\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/SampleServletTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockObjectFactory;\nimport org.testng.IObjectFactory;\nimport org.testng.annotations.ObjectFactory;\nimport org.testng.annotations.Test;\nimport samples.servletmocking.SampleServlet;\n\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.PrintWriter;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\n\n@PrepareForTest(SampleServlet.class)\npublic class SampleServletTest {\n\n    @Test\n    public void doGet() throws Exception {\n        SampleServlet servlet = new SampleServlet();\n\n        HttpServletResponse response = createMock(HttpServletResponse.class);\n        PrintWriter writer = createMock(PrintWriter.class);\n\n        expect(response.getWriter()).andReturn(writer);\n        writer.write(\"out\");\n\n        replay(response, writer);\n\n        servlet.doGet(null, response);\n\n        verify(response, writer);\n    }\n\n    @ObjectFactory\n    public IObjectFactory getObjectFactory() {\n        return new PowerMockObjectFactory();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/src/test/java/samples/testng/agent/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.testng.agent;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.annotations.Test;\nimport samples.system.SystemClassUser;\n\nimport java.net.InetAddress;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.easymock.EasyMock.anyLong;\nimport static org.easymock.EasyMock.expect;\nimport static org.powermock.api.easymock.PowerMock.*;\nimport static org.testng.Assert.assertSame;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.AssertJUnit.assertEquals;\n\n/**\n * Demonstrates PowerMock's ability to mock non-final and final system classes.\n * To mock a system class you need to prepare the calling class for testing.\n * I.e. let's say you're testing class A which interacts with URLEncoder then\n * you would do:\n *\n * <pre>\n *\n * &#064;PrepareForTest({A.class})\n *\n * </pre>\n */\n@PrepareForTest( { SystemClassUser.class })\npublic class SystemClassUserTest extends PowerMockTestCase {\n\n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n\n        expect(URLEncoder.encode(\"string\", \"enc\")).andReturn(\"something\");\n        replayAll();\n\n        assertEquals(\"something\", new SystemClassUser().performEncode());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n\n        Runtime runtimeMock = createMock(Runtime.class);\n        Process processMock = createMock(Process.class);\n\n        expect(Runtime.getRuntime()).andReturn(runtimeMock);\n        expect(runtimeMock.exec(\"command\")).andReturn(processMock);\n\n        replayAll();\n\n        assertSame(processMock, new SystemClassUser().executeCommand());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n\n        expect(System.getProperty(\"property\")).andReturn(\"my property\");\n\n        replayAll();\n\n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStaticPartial(System.class, \"nanoTime\");\n\n        expect(System.nanoTime()).andReturn(2L);\n\n        replayAll();\n\n        new SystemClassUser().doMoreComplicatedStuff();\n\n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        mockStaticPartial(System.class, \"getProperty\");\n\n        expect(System.getProperty(\"property\")).andReturn(\"my property\");\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n\n        Collections.shuffle(list);\n        expectLastCall().once();\n\n        replayAll();\n\n        new SystemClassUser().shuffleCollection(list);\n\n        verifyAll();\n    }\n\n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n\n        expect(String.format(string, args)).andReturn(returnValue);\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingStaticVoidMethodWorks() throws Exception {\n        mockStatic(Thread.class);\n\n        Thread.sleep(anyLong());\n        expectLastCall().once();\n\n        replayAll();\n\n        long startTime = System.currentTimeMillis();\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.threadSleep();\n        long endTime = System.currentTimeMillis();\n        assertTrue(endTime - startTime < 5000);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingInstanceMethodOfFinalSystemClassWorks() throws Exception {\n        URL url = createMock(URL.class);\n        URLConnection urlConnection = createMock(URLConnection.class);\n\n        expect(url.openConnection()).andStubReturn(urlConnection);\n\n        replayAll();\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertSame(urlConnection, systemClassUser.useURL(url));\n        verifyAll();\n    }\n\n    @Test\n    public void mockingURLWorks() throws Exception {\n        URL url = createMock(URL.class);\n        URLConnection urlConnectionMock = createMock(URLConnection.class);\n\n        expect(url.openConnection()).andReturn(urlConnectionMock);\n\n        replayAll();\n\n        assertSame(url.openConnection(), urlConnectionMock);\n\n        verifyAll();\n    }\n\n    @Test\n    public void mockingInetAddressWorks() throws Exception {\n        final InetAddress mock = createMock(InetAddress.class);\n        mockStatic(InetAddress.class);\n\n        expect(InetAddress.getLocalHost()).andReturn(mock);\n\n        replayAll();\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertSame(mock, systemClassUser.getLocalHost());\n\n        verifyAll();\n    }\n}\n"
  },
  {
    "path": "tests/easymock/testng-agent/suite.xml",
    "content": "<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name=\"dgf\" verbose=\"10\" object-factory=\"org.powermock.modules.testng.PowerMockObjectFactory\">\n    <test name=\"dgf\">\n        <classes>\n            <class name=\"samples.testng.agent.FinalDemoTest\"/>\n            <class name=\"samples.testng.agent.AnnotationDemoTest\"/>\n        \t<class name=\"samples.testng.agent.AnnotationDemoWithBeforeMethodTest\"/>\n            <class name=\"samples.testng.agent.PrivateFinalTest\"/>\n            <class name=\"samples.testng.agent.MockStaticExtendsPowerMockTestCaseTest\"/>\n            <class name=\"samples.testng.agent.PartialMockingWithBeforeClassTest\"/>\n            <class name=\"samples.testng.agent.PrivateFinalTest\"/>\n            <class name=\"samples.testng.agent.SystemClassUserTest\" />\n            <class name=\"samples.testng.agent.SampleServletTest\" />\n            <class name=\"samples.testng.agent.NotAnnotatedWithPrepareForTest\" />\n        </classes>\n    </test>\n</suite>"
  },
  {
    "path": "tests/java11/build.gradle",
    "content": "configure(project.subprojects) { subproject ->\n\n    // TODO: uncomment the followings once gradle supports JDK11\n//    if (JavaVersion.current() != JavaVersion.VERSION_11) {\n//        project.tasks.all { task -> task.enabled = false }\n//    }\n\n    dependencies {\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n\n    // TODO: uncomment the followings once JDK11 is supported\n//    compileJava {\n//        sourceCompatibility = 11\n//        targetCompatibility = 11\n//    }\n//\n//    compileTestJava {\n//        sourceCompatibility = 11\n//        targetCompatibility = 11\n//    }\n}\n\nproject(\":tests:java11:mockito-junit4\") {\n    description = \"Tests for Mockito module with JUnit 4.x. and Java11.\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4\")\n\n        testCompile project(\":powermock-api:powermock-api-mockito2\")\n        testCompile (\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n    }\n}\n"
  },
  {
    "path": "tests/java11/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github958/OuterClass.java",
    "content": "package samples.powermockito.junit4.bugs.github958;\n\npublic class OuterClass {\n  public static InnerSingleton theInstance = new InnerSingleton();\n  public static class InnerSingleton {\n    public String name = \"inner\";\n    private InnerSingleton() {}\n  }\n}\n"
  },
  {
    "path": "tests/java11/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github958/Github958Test.java",
    "content": "package samples.powermockito.junit4.bugs.github958;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(OuterClass.class)\npublic class Github958Test {\n  @Test\n  public void test() {\n    assertEquals(\"inner\", OuterClass.theInstance.name);\n  }\n}\n"
  },
  {
    "path": "tests/java8/build.gradle",
    "content": "configure(project.subprojects) { subproject ->\n\n    if (JavaVersion.current() != JavaVersion.VERSION_1_8) {\n        project.tasks.all { task -> task.enabled = false }\n    }\n\n    dependencies {\n        testCompile(\"junit:junit:${junitVersion}\") {\n            exclude group: 'org.hamcrest', module: 'hamcrest-core'\n        }\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n\n    compileJava {\n        sourceCompatibility = 1.8\n        targetCompatibility = 1.8\n    }\n\n    compileTestJava {\n        sourceCompatibility = 1.8\n        targetCompatibility = 1.8\n    }\n}\n\nproject(\":tests:java8:mockito-junit4\") {\n    description = \"Tests for Mockito module with JUnit 4.x. and Java8.\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4\")\n\n        testCompile project(\":powermock-api:powermock-api-mockito2\")\n        testCompile (\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n    }\n}\n\nproject(\":tests:java8:easymock-junit4\") {\n    description = \"Tests for Easymock module with JUnit 4.x. and Java8.\"\n\n    dependencies {\n        testCompile project(\":powermock-api:powermock-api-easymock\")\n        testCompile project(\":powermock-modules:powermock-module-junit4\")\n        testCompile(\"org.easymock:easymock:${easymockVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n    }\n}\n\nproject(\":tests:java8:mockito-junit4-agent\") {\n    description = \"Tests for Mockito module with JUnit 4.x. and Java8.\"\n\n    dependencies {\n        testCompile project(\":powermock-api:powermock-api-mockito2\")\n        testCompile (\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n\n        testCompile project(\":powermock-modules:powermock-module-junit4-rule-agent\")\n    }\n\n    def pathToAgent = project(\":powermock-modules:powermock-module-javaagent\").jar.outputs.files.getFiles().getAt(0)\n\n    test {\n        jvmArgs \"-javaagent:${pathToAgent}\"\n    }\n}\n\nproject(\":tests:java8:mockito-junit4-rule-xstream\") {\n    description = \"Tests for Mockito module with JUnit 4.x, Java8 and rules-xstream.\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4-rule\")\n        testCompile project(\":powermock-classloading:powermock-classloading-xstream\")\n\n        testCompile project(\":powermock-api:powermock-api-mockito2\")\n        testCompile (\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n}"
  },
  {
    "path": "tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/Instance.java",
    "content": "package samples.powermockito.junit4.bugs.github717;\n\npublic class Instance {\n}\n"
  },
  {
    "path": "tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/InstanceFacade.java",
    "content": "package samples.powermockito.junit4.bugs.github717;\n\npublic interface InstanceFacade {\n}\n"
  },
  {
    "path": "tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/InstanceFacadeImpl.java",
    "content": "package samples.powermockito.junit4.bugs.github717;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.function.Consumer;\n\npublic class InstanceFacadeImpl implements InstanceFacade {\n    \n    final Map<InstanceStatus, Consumer<Instance>> instanceStatusProcessors = new HashMap<>();\n    \n    {\n        instanceStatusProcessors.put(InstanceStatus.PENDING, instance -> {\n            // NOP\n        });\n    }\n    \n}\n"
  },
  {
    "path": "tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/InstanceStatus.java",
    "content": "package samples.powermockito.junit4.bugs.github717;\n\npublic enum InstanceStatus {\n    PENDING\n}\n"
  },
  {
    "path": "tests/java8/easymock-junit4/src/test/java/samples/powermockito/junit4/bugs/github717/InstanceFacadeImplTest.java",
    "content": "package samples.powermockito.junit4.bugs.github717;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.extension.listener.AnnotationEnabler;\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.powermock.api.easymock.PowerMock.replayAll;\nimport static org.powermock.api.easymock.PowerMock.verifyAll;\n\n@RunWith(PowerMockRunner.class)\n@PowerMockListener(AnnotationEnabler.class)\n@PrepareForTest(InstanceFacadeImpl.class)\npublic class InstanceFacadeImplTest {\n    \n    private InstanceFacadeImpl instanceFacade;\n    \n    @Before\n    public void setup() throws Exception {\n        instanceFacade = new InstanceFacadeImpl();\n    }\n    \n    @Test\n    public void should_not_throw_exception() throws Exception {\n        replayAll();\n        instanceFacade.instanceStatusProcessors.get(InstanceStatus.PENDING).accept(null);\n        verifyAll();\n    }\n    \n}\n"
  },
  {
    "path": "tests/java8/easymock-junit4/src/test/java/samples/powermockito/junit4/bugs/github717/package-info.java",
    "content": "/**\n * Regression: MethodNotFoundException\n * https://github.com/powermock/powermock/issues/717\n *\n * org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) accept were found in the class hierarchy of class java.lang.Object.\n at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1720)\n at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1745)\n at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:983)\n at org.powermock.core.MockGateway$MockInvocation.findMethodToInvoke(MockGateway.java:317)\n at org.powermock.core.MockGateway$MockInvocation.init(MockGateway.java:356)\n at org.powermock.core.MockGateway$MockInvocation.<init>(MockGateway.java:307)\n at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:142)\n at org.powermock.core.MockGateway.methodCall(MockGateway.java:125)\n at InstanceFacadeImplTest.pendingInstanceStatusProcessorShouldDoNothing(InstanceFacadeI\n *\n */\npackage samples.powermockito.junit4.bugs.github717;"
  },
  {
    "path": "tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterface.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\n/**\n *\n */\npublic class ClassUsesInterface {\n\n    public String saySomething(){\n        return InterfaceWithStatic.sayHello();\n    }\n\n    public String createAndSay(){\n        return InterfaceWithStatic.createAndSay();\n    }\n\n}\n"
  },
  {
    "path": "tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github510/ConstructorObject.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\n/**\n *\n */\npublic class ConstructorObject {\n    public String sayHello() {\n        return null;\n    }\n}\n"
  },
  {
    "path": "tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github510/InterfaceWithStatic.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\n/**\n *\n */\npublic interface InterfaceWithStatic {\n\n    static String sayHello(){\n        return \"What's up?\";\n    }\n\n    static  String createAndSay(){\n        return new ConstructorObject().sayHello();\n    }\n\n}\n"
  },
  {
    "path": "tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/largemethod/InterfaceMethodExceedingJvmLimit.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.largemethod;\n\n/**\n * Example of class with method which after instrumentation is larger than JVM limit.\n */\npublic interface InterfaceMethodExceedingJvmLimit {\n\n\t/**\n\t * Method size after instrumentation is equal to 91265.\n\t */\n\tstatic String init() {\n\t\tString a = \"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\treturn a;\n\t}\n}"
  },
  {
    "path": "tests/java8/mockito-junit4/src/test/java/org/powermock/modules/junit4/largemethod/LargeMethodInInterfaceTest.java",
    "content": "package org.powermock.modules.junit4.largemethod;\r\n\r\nimport org.junit.Test;\r\nimport org.junit.runner.RunWith;\r\nimport org.powermock.api.mockito.PowerMockito;\r\nimport org.powermock.core.classloader.annotations.PrepareForTest;\r\nimport org.powermock.modules.junit4.PowerMockRunner;\r\nimport samples.powermockito.junit4.largemethod.InterfaceMethodExceedingJvmLimit;\r\n\r\nimport static junit.framework.Assert.assertEquals;\r\nimport static junit.framework.Assert.assertNull;\r\nimport static junit.framework.Assert.assertSame;\r\nimport static junit.framework.Assert.assertTrue;\r\nimport static junit.framework.Assert.fail;\r\nimport static org.mockito.Mockito.when;\r\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\r\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\r\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\r\n\r\n@RunWith(PowerMockRunner.class)\r\n@PrepareForTest(InterfaceMethodExceedingJvmLimit.class)\r\npublic class LargeMethodInInterfaceTest {\r\n\r\n    @Test\r\n    public void largeMethodShouldBeOverridden() {\r\n        try {\r\n            InterfaceMethodExceedingJvmLimit.init();\r\n            fail(\"Method should be overridden and exception should be thrown\");\r\n        } catch (Exception e) {\r\n            assertSame(IllegalAccessException.class, e.getClass());\r\n            assertTrue(e.getMessage().contains(\"Method was too large and after instrumentation exceeded JVM limit\"));\r\n        }\r\n    }\r\n\r\n    @Test\r\n    public void largeMethodShouldBeAbleToBeSuppressed() {\r\n        suppress(PowerMockito.method(InterfaceMethodExceedingJvmLimit.class, \"init\"));\r\n        assertNull(\"Suppressed method should return: null\", InterfaceMethodExceedingJvmLimit.init());\r\n    }\r\n\r\n    @Test\r\n    public void largeMethodShouldBeAbleToBeMocked() {\r\n        mockStatic(InterfaceMethodExceedingJvmLimit.class);\r\n        when(InterfaceMethodExceedingJvmLimit.init()).thenReturn(\"ok\");\r\n        assertEquals(\"Mocked method should return: ok\", \"ok\", InterfaceMethodExceedingJvmLimit.init());\r\n        verifyStatic(InterfaceMethodExceedingJvmLimit.class);\r\n        InterfaceMethodExceedingJvmLimit.init();\r\n    }\r\n\r\n    @Test(expected = IllegalStateException.class)\r\n    public void largeMethodShouldBeAbleToBeMockedAndThrowException() {\r\n        mockStatic(InterfaceMethodExceedingJvmLimit.class);\r\n        when(InterfaceMethodExceedingJvmLimit.init()).thenThrow(new IllegalStateException());\r\n        InterfaceMethodExceedingJvmLimit.init();\r\n        verifyStatic(InterfaceMethodExceedingJvmLimit.class);\r\n        InterfaceMethodExceedingJvmLimit.init();\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/Github510Test.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.mockito.PowerMockito.whenNew;\n\n/**\n *\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({InterfaceWithStatic.class, ConstructorObject.class})\npublic class Github510Test {\n\n    public ClassUsesInterface classUsesInterface;\n\n    @Before\n    public void setUp() throws Exception {\n        classUsesInterface = new ClassUsesInterface();\n    }\n\n    @Test\n    public void testSaySomething() throws Exception {\n        final String value = \"Hi Man\";\n\n        mockStatic(InterfaceWithStatic.class);\n        when(InterfaceWithStatic.sayHello()).thenReturn(value);\n\n        assertThat(classUsesInterface.saySomething()).isEqualTo(value);\n    }\n\n    @Test\n    public void testInterfaceStaticCallsConstructor() throws Exception {\n        final String value = \"Hi Man\";\n\n        ConstructorObject constructorObject = mock(ConstructorObject.class);\n        when(constructorObject.sayHello()).thenReturn(value);\n\n\n        whenNew(ConstructorObject.class).withNoArguments().thenReturn(constructorObject);\n\n        assertThat(classUsesInterface.createAndSay()).isEqualTo(value);\n    }\n}"
  },
  {
    "path": "tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/package-info.java",
    "content": "/**\n * https://github.com/jayway/powermock/issues/510\n */\npackage samples.powermockito.junit4.bugs.github510;"
  },
  {
    "path": "tests/java8/mockito-junit4-agent/src/main/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterface.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\n/**\n *\n */\npublic class ClassUsesInterface {\n\n    public String saySomething(){\n        return InterfaceWithStatic.sayHello();\n    }\n\n}\n"
  },
  {
    "path": "tests/java8/mockito-junit4-agent/src/main/java/samples/powermockito/junit4/bugs/github510/InterfaceWithStatic.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\n/**\n *\n */\npublic interface InterfaceWithStatic {\n\n    static String sayHello(){\n        return \"What's up?\";\n    }\n\n}\n"
  },
  {
    "path": "tests/java8/mockito-junit4-agent/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n/**\n *\n */\n@PrepareForTest(InterfaceWithStatic.class)\npublic class ClassUsesInterfaceTest {\n\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    public ClassUsesInterface classUsesInterface;\n\n    @Before\n    public void setUp() throws Exception {\n        classUsesInterface = new ClassUsesInterface();\n\n        mockStatic(InterfaceWithStatic.class);\n    }\n\n    @Test\n    public void testSaySomething() throws Exception {\n        final String value = \"Hi Man\";\n        when(InterfaceWithStatic.sayHello()).thenReturn(value);\n\n        assertThat(classUsesInterface.saySomething()).isEqualTo(value);\n    }\n}"
  },
  {
    "path": "tests/java8/mockito-junit4-rule-xstream/src/main/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterface.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\n/**\n *\n */\npublic class ClassUsesInterface {\n\n    public String saySomething(){\n        return InterfaceWithStatic.sayHello();\n    }\n\n}\n"
  },
  {
    "path": "tests/java8/mockito-junit4-rule-xstream/src/main/java/samples/powermockito/junit4/bugs/github510/InterfaceWithStatic.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\n/**\n *\n */\npublic interface InterfaceWithStatic {\n\n    static String sayHello(){\n        return \"What's up?\";\n    }\n\n}\n"
  },
  {
    "path": "tests/java8/mockito-junit4-rule-xstream/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java",
    "content": "package samples.powermockito.junit4.bugs.github510;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n/**\n *\n */\n@PrepareForTest(InterfaceWithStatic.class)\npublic class ClassUsesInterfaceTest {\n\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    public ClassUsesInterface classUsesInterface;\n\n    @Before\n    public void setUp() throws Exception {\n        classUsesInterface = new ClassUsesInterface();\n\n        mockStatic(InterfaceWithStatic.class);\n    }\n\n\n    @Test\n    public void testSaySomething() throws Exception {\n        final String value = \"Hi Man\";\n        when(InterfaceWithStatic.sayHello()).thenReturn(value);\n\n        assertThat(classUsesInterface.saySomething()).isEqualTo(value);\n    }\n}"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/GitHub352Test.java",
    "content": "package samples.powermockito.junit4.bugs.github352;\n\nimport org.junit.Test;\nimport org.junit.runner.JUnitCore;\nimport org.junit.runner.Request;\nimport org.junit.runner.Result;\nimport org.junit.runner.Runner;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class GitHub352Test {\n\n\n    @Test\n    public void testCountShouldBe3WhenRunWithDefaultRunner() {\n        JUnitCore jUnitCore = new JUnitCore();\n\n        Result result = jUnitCore.run(MyTest.class);\n\n        int testCount = result.getRunCount();\n        assertThat(testCount).describedAs(\"Test count not match to expected.\", 3).isEqualTo(3);\n    }\n\n    @Test\n    public void testCountShouldBe3WhenRunWithPowerMockRunner() {\n        JUnitCore jUnitCore = new JUnitCore();\n\n        Request request = new Request() {\n            @Override\n            public Runner getRunner() {\n                try {\n                    return new PowerMockRunner(MyTest.class);\n                } catch (Exception e) {\n                    throw  new RuntimeException(e);\n                }\n            }\n        };\n\n\n        Result result = jUnitCore.run(request);\n\n        int testCount = result.getRunCount();\n        assertThat(testCount).describedAs(\"Test count not match to expected.\", 3).isEqualTo(3);\n    }\n}\n"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/MyAbstractTest.java",
    "content": "package samples.powermockito.junit4.bugs.github352;\n\nimport org.junit.Test;\n\n/**\n *\n */\npublic abstract class MyAbstractTest {\n\n\n    @Test\n    public abstract void  test1();\n\n    @Test\n    public abstract void test2();\n\n}\n"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/MyTest.java",
    "content": "package samples.powermockito.junit4.bugs.github352;\n\nimport org.junit.Test;\n\n/**\n *\n */\npublic class MyTest extends MyAbstractTest {\n\n    //some setup code here\n\n    @Override\n    public void test1() {\n        //some test code here\n    }\n\n    @Override\n    public void test2() {\n        //some test code here\n    }\n\n    @Test\n    public void test3() {\n        // some test code here\n    }\n\n}\n"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/package-info.java",
    "content": "/**\n * https://github.com/jayway/powermock/issues/352\n */\npackage samples.powermockito.junit4.bugs.github352;"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/GitHub722Test.java",
    "content": "package samples.powermockito.junit4.bugs.github722;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.contrib.java.lang.system.DisallowWriteToSystemErr;\nimport org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner;\nimport org.powermock.reflect.Whitebox;\n\nimport java.lang.reflect.Method;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class GitHub722Test {\n\n    @Rule\n    public final DisallowWriteToSystemErr disallowWriteToSystemErr = new DisallowWriteToSystemErr();\n\n    @Test\n    public void testDelegatingPowerMockRunnerUseTheories() throws Exception {\n\n        String[] methodsToRun = {\"testUseTheoriesTest\"};\n        DelegatingPowerMockRunner test = new DelegatingPowerMockRunner(UseTheoriesTest.class, methodsToRun, null);\n        Method[] methods = Whitebox.getInternalState(test, \"testMethods\");\n        String expected = \"testUseTheoriesTest\";\n        int expectedSize = 1;\n        assertThat(methods.length).describedAs(\"Check array size\").isEqualTo(expectedSize);\n        assertThat(methods[0].getName()).describedAs(\"Test using Theory annotation\").isEqualTo(expected);\n    }\n\n    @Test\n    public void testDelegatingPowerMockRunnerUseJUnit() throws Exception {\n\n        String[] methodsToRun = {\"testJUnitTest\"};\n        DelegatingPowerMockRunner test = new DelegatingPowerMockRunner(UseJUnitTest.class, methodsToRun, null);\n        Method[] methods = Whitebox.getInternalState(test, \"testMethods\");\n        String expected = \"testJUnitTest\";\n        int expectedSize = 1;\n        assertThat(methods.length).describedAs(\"Check array size\").isEqualTo(expectedSize);\n        assertThat(methods[0].getName()).describedAs(\"Test using Theory annotation\").isEqualTo(expected);\n    }\n}\n"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseJUnitTest.java",
    "content": "package samples.powermockito.junit4.bugs.github722;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n@RunWith(PowerMockRunner.class)\npublic class UseJUnitTest {\n\n    @Test\n    public void testJUnitTest() {\n        //some test code here\n    }\n}\n"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseTheoriesTest.java",
    "content": "package samples.powermockito.junit4.bugs.github722;\n\nimport org.junit.runner.RunWith;\nimport org.junit.experimental.theories.Theories;\nimport org.junit.experimental.theories.Theory;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\n\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Theories.class)\npublic class UseTheoriesTest {\n\n    @Theory\n    public void testUseTheoriesTest() {\n        //some test code here\n    }\n}\n"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github733/GitHub733Test.java",
    "content": "package samples.powermockito.junit4.bugs.github733;\n\nimport org.junit.Test;\nimport org.powermock.modules.junit4.internal.impl.testcaseworkaround.PowerMockJUnit4MethodValidator;\n\npublic class GitHub733Test {\n\n    @Test\n    public void testPowerMockJUnit4MethodValidatorAcceptsTestAnnotatedMethods() throws Exception {\n    \n        PowerMockJUnit4MethodValidator validator = new PowerMockJUnit4MethodValidator(new UseTestAnnotatedTest(UseTestAnnotatedTest.MethodToTest.class));\n        validator.validateInstanceMethods();\n    }\n}\n"
  },
  {
    "path": "tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github733/UseTestAnnotatedTest.java",
    "content": "package samples.powermockito.junit4.bugs.github733;\n\nimport org.junit.Test;\nimport org.junit.experimental.runners.Enclosed;\nimport org.junit.internal.runners.TestClass;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n@RunWith(Enclosed.class)\npublic class UseTestAnnotatedTest extends TestClass {\n\n    public UseTestAnnotatedTest(Class<MethodToTest> klass) {\n        super(klass);\n    }\n\n    @RunWith(PowerMockRunner.class)\n    public static class MethodToTest {\n\n        @Test\n        public void genericMethod() {\n            // no prefix of test for method name\n        }\n\n    }\n\n\n}\n"
  },
  {
    "path": "tests/mockito/build.gradle",
    "content": "configure(project.subprojects){ subproject ->\n\n    dependencies {\n        testCompile project(\":tests:utils\")\n\n        testCompile(\"org.hamcrest:hamcrest-core:${hamcrestVersion}\")\n        testCompile(\"org.assertj:assertj-core:${assertjVersion}\")\n\n        testCompile project(\":powermock-api:powermock-api-mockito2\")\n        testCompile (\"org.mockito:mockito-core:${mockitoVersion}\"){\n            exclude group: 'net.bytebuddy', module: 'byte-buddy'\n            exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'\n        }\n    }\n}\n\nproject(\":tests:mockito:junit4\") {\n    description = \"Tests for Mockito module with JUnit 4.x.\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4\")\n\n        testCompile(\"junit:junit:${junitVersion}\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n\n        testCompile (\"org.jacoco:org.jacoco.core:${jacocoVersion}\")\n        testCompile (\"org.eclipse.jdt:core:${eclipseJdt}\")\n    }\n\n    test{\n        exclude \"**/*Cases*\"\n    }\n}\n\nproject(\":tests:mockito:inline\") {\n    description = \"Tests for Mockito 2 inline mock maker\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4\")\n\n        testCompile(\"junit:junit:${junitVersion}\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n    }\n\n    test{\n        exclude \"**/*Cases*\"\n    }\n}\n\nproject(\":tests:mockito:junit49\") {\n    description = \"Tests for Mockito module with JUnit 4.9.x.\"\n\n    dependencies {\n        testCompile project(\":tests:utils\")\n        testCompile project(\":powermock-modules:powermock-module-junit4\")\n\n        testCompile(\"junit:junit:4.9\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n    }\n}\n\nproject(\":tests:mockito:junit4-agent\"){\n    description = \"Tests for PowerMock Java agent with JUnit4 and Mockito.\"\n\n    dependencies {\n\n        testCompile project(\":powermock-modules:powermock-module-junit4-rule-agent\")\n\n        testCompile(\"junit:junit:${junitVersion}\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n\n    def pathToAgent = project(\":powermock-modules:powermock-module-javaagent\").jar.outputs.files.getFiles().getAt(0)\n\n    test {\n        jvmArgs \"-javaagent:${pathToAgent}\"\n    }\n}\n\n\nproject(\":tests:mockito:junit4-rule-objenesis\") {\n    description = \"Tests for PowerMock Rule using Objenesis Deepcloning.\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4-rule\")\n        testCompile project(\":powermock-classloading:powermock-classloading-objenesis\")\n\n        testCompile(\"junit:junit:${junitVersion}\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n}\n\nproject(\":tests:mockito:junit4-rule-xstream\") {\n    description = \"Tests for PowerMock Rule using Xstream Deepcloning.\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4-rule\")\n        testCompile project(\":powermock-classloading:powermock-classloading-xstream\")\n\n        testCompile(\"junit:junit:${junitVersion}\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n}\n\nproject(\":tests:mockito:junit4-delegate\") {\n    description = \"Tests for PowerMock JUnit4 runner-delegate and Mockito.\"\n\n    dependencies {\n        testCompile project(\":powermock-modules:powermock-module-junit4\")\n\n        testCompile(\"junit:junit:${junitVersion}\"){\n            exclude group:'org.hamcrest', module:'hamcrest-core'\n        }\n\n        testCompile(\"pl.pragmatists:JUnitParams:1.0.5\")\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n\n    test{\n        scanForTestClasses = false\n        include([\"**/*Tests.class\", \"**/*Test.class\"])\n        // Since we set scanForTestClasses to false, we need to filter out inner\n        // classes with the \"$\" pattern; otherwise, using -Dtest.single=MyTests to\n        // run MyTests by itself will fail if MyTests contains any inner classes.\n        exclude([\"**/Abstract*.class\", '**/*$*'])\n    }\n}\n\nproject(\":tests:mockito:testng\"){\n    description = \"Tests for Mockito module with TestNG.\"\n\n    dependencies {\n        testCompile(project(\":powermock-core\"))\n        testCompile(project(\":powermock-modules:powermock-module-testng\"))\n\n        testCompile(\"org.testng:testng:${testngVersion}\")\n\n        testCompile files(project(\":tests:mockito:junit4\").sourceSets.test.output)\n    }\n\n    test{\n        useTestNG(){\n            suites 'suite.xml'\n            environment \"mockitoVersion\", \"${mockitoVersion}\"\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/inline/src/main/java/samples/powermockito/inline/bugs/github793/FinalClass.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.inline.bugs.github793;\n\npublic final class FinalClass {\n    \n    public String ask(){\n        return \"Hello, man!\";\n    }\n    \n    public final void say(String message){\n        throw new RuntimeException(message);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/inline/src/main/java/samples/powermockito/inline/bugs/github793/StaticClass.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.inline.bugs.github793;\n\npublic class StaticClass {\n    \n    public static String ask(){\n        return \"Hello, man!\";\n    }\n    \n    public static void say(String message){\n        throw new RuntimeException(message);\n    }\n    \n}\n"
  },
  {
    "path": "tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/MockitoFinalClassMockingTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.inline.bugs.github793;\n\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.mockito.Mockito;\nimport org.powermock.api.mockito.MockitoVersion;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.catchThrowable;\nimport static org.junit.Assume.assumeTrue;\nimport static org.mockito.Mockito.doNothing;\nimport static org.mockito.Mockito.when;\n\npublic class MockitoFinalClassMockingTest {\n    \n    @Test\n    public void should_mock_final_class_with_using_mockito_inline_mock_creator() {\n        \n        assumeTrue(\"Test make seances only for Mockito 2\", MockitoVersion.isMockito2());\n        \n        FinalClass mock = Mockito.mock(FinalClass.class);\n        \n        String value = \"Why me?\";\n        \n        when(mock.ask()).thenReturn(value);\n        \n        assertThat(mock.ask())\n            .as(\"Mock for final class works\")\n            .isEqualTo(value);\n    }\n    \n    @Test\n    public void should_mock_final_method_with_using_mockito_inline_mock_creator() {\n        \n        assumeTrue(\"Test make seances only for Mockito 2\", MockitoVersion.isMockito2());\n        \n        final FinalClass mock = Mockito.mock(FinalClass.class);\n        \n        final String value = \"Why me?\";\n        \n        doNothing().when(mock).say(value);\n        \n        Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                mock.say(value);\n            }\n        });\n        \n        assertThat(throwable)\n            .as(\"Mock for final method works\")\n            .isNull();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PartialMockingExampleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.inline.bugs.github793;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.partialmocking.PartialMockingExample;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.doReturn;\nimport static org.powermock.api.mockito.PowerMockito.spy;\n\n/**\n * Asserts that partial mocking (spying) with PowerMockito works for non-final\n * methods.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PartialMockingExample.class)\npublic class PartialMockingExampleTest {\n    @Test\n\tpublic void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocations() throws Exception {\n\t\tfinal String expected = \"TEST VALUE\";\n\t\tPartialMockingExample underTest = spy(new PartialMockingExample());\n\t\tdoReturn(expected).when(underTest).methodToMock();\n\n\t\tassertEquals(expected, underTest.methodToTest());\n\n\t\tverify(underTest).methodToTest();\n\t\tverify(underTest).methodToMock();\n\t}\n\t\n\t@Test\n\tpublic void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocationsForMockito() throws Exception {\n\t\tfinal String expected = \"TEST VALUE\";\n\t\tPartialMockingExample underTest = Mockito.spy(new PartialMockingExample());\n\t\tdoReturn(expected).when(underTest).methodToMock();\n\n\t\tassertEquals(expected, underTest.methodToTest());\n\n\t\tverify(underTest).methodToTest();\n\t\tverify(underTest).methodToMock();\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PowerMockStaticMockingTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.inline.bugs.github793;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.exceptions.verification.NoInteractionsWanted;\nimport org.powermock.api.mockito.MockitoVersion;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.junit.Assume.assumeTrue;\nimport static org.mockito.Mockito.when;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticClass.class)\npublic class PowerMockStaticMockingTest {\n    \n    @Test\n    public void should_mock_static_method_when_mockito_inline_mock_creator_for_mockito_tests() {\n\n        assumeTrue(\"Test makes sense only for Mockito 2 & 3 & 4\",\n                MockitoVersion.isMockito2() || MockitoVersion.isMockito3() || MockitoVersion.isMockito4());\n    \n        PowerMockito.mockStatic(StaticClass.class);\n        \n        String value = \"Why me?\";\n        \n        when(StaticClass.ask()).thenReturn(value);\n        \n        assertThat(StaticClass.ask())\n            .as(\"Mock for static method works\")\n            .isEqualTo(value);\n    }\n    \n    @Test\n    public void should_verify_static_method_when_mockito_inline_mock_creator_for_mockito_tests() throws Exception {\n\n        assumeTrue(\"Test makes sense only for Mockito 2 & 3 & 4\",\n                MockitoVersion.isMockito2() || MockitoVersion.isMockito3() || MockitoVersion.isMockito4());\n    \n        PowerMockito.mockStatic(StaticClass.class);\n    \n        final String value = \"Why me?\";\n    \n        PowerMockito.doNothing().when(StaticClass.class,\"say\", value);\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                StaticClass.say(value);\n                PowerMockito.verifyNoMoreInteractions(StaticClass.class);\n            }\n        }).as(\"Verify exception is thrown\")\n          .isInstanceOf(NoInteractionsWanted.class);\n    }\n    \n}\n"
  },
  {
    "path": "tests/mockito/inline/src/test/resources/org/powermock/extensions/configuration.properties",
    "content": "mockito.mock-maker-class=mock-maker-inline"
  },
  {
    "path": "tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github731/AType.java",
    "content": "package samples.powermockito.junit4.bugs.github731;\n\npublic class AType {\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github731/OptionalInterface.java",
    "content": "package samples.powermockito.junit4.bugs.github731;\n\npublic interface OptionalInterface<T> {\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github731/SomeInterface.java",
    "content": "package samples.powermockito.junit4.bugs.github731;\n\npublic interface SomeInterface<T> {\n    T get();\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnore.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.bugs.github801;\n\npublic class GlobalPowerMockIgnore {\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github806/CustomException.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.bugs.github806;\n\npublic class CustomException extends Exception {\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github806/DoThrowTMockClass.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.bugs.github806;\n\npublic class DoThrowTMockClass {\n    \n    public void doSomething() {\n    \n    }\n    \n    public void throwExceptionForInput(String foo) throws CustomException {\n        if (\"123\".equals(foo)) {\n            throw new CustomException();\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClass.java",
    "content": "package samples.powermockito.junit4;\n\n/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Just a testclass with a final-equals method.\n */\npublic class FinalEqualsClass {\n\n    @Override\n    public final boolean equals(Object obj) {\n        return super.equals(obj);\n    }\n\n    public final String foo() {\n        return \"foo\";\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClassTest.java",
    "content": "package samples.powermockito.junit4;\n\n\nimport static org.junit.Assert.*;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\n/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n@RunWith(value = PowerMockRunner.class)\n@PrepareForTest({FinalEqualsClass.class})\n@SuppressStaticInitializationFor({\"samples.powermockito.junit4.FinalClass\"})\npublic class FinalEqualsClassTest {\n\n    @Test\n    public void callingEqualsDoesntCauseStackOverflow() throws Exception {\n        FinalEqualsClass fc = new FinalEqualsClass();\n        fc.foo();\n\n        FinalEqualsClass mock = PowerMockito.mock(FinalEqualsClass.class);\n        FinalEqualsClass mock2 = PowerMockito.mock(FinalEqualsClass.class);\n        PowerMockito.when(mock.foo()).thenReturn(\"bar\");\n        fc = PowerMockito.spy(fc);\n        PowerMockito.when(fc.foo()).thenReturn(\"bar\");\n        fc.equals(mock);\n        assertEquals(\"bar\", mock.foo());\n        assertEquals(\"bar\", fc.foo());\n\n        assertEquals(mock, mock);\n        assertFalse(mock.equals(mock2));\n\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/abstractmocking/AbstractMethodMockingTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.abstractmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.abstractmocking.AbstractMethodMocking;\n\nimport static org.junit.Assert.*;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { AbstractMethodMocking.class })\npublic class AbstractMethodMockingTest {\n\n    @Test\n    public void mocksAbstractClasses() throws Exception {\n        assertNotNull(mock(AbstractMethodMocking.class));\n    }\n\n    @Test\n    public void canSpyOnAnonymousClasses() throws Exception {\n        AbstractMethodMocking tested = new AbstractMethodMocking() {\n            @Override\n            protected String getIt() {\n                return null;\n            }\n        };\n\n        assertNull(tested.getValue());\n        AbstractMethodMocking spy = spy(tested);\n        when(spy.getValue()).thenReturn(\"something\");\n\n        assertEquals(\"something\", spy.getValue());\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/CaptorAnnotationTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.ArgumentCaptor;\nimport org.mockito.Captor;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\nimport samples.privateandfinal.PrivateFinal;\nimport samples.privateandfinal.PrivateFinalOverload;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.ArgumentMatchers.anyString;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n/**\n * Asserts that {@link Captor} with PowerMock.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({FinalDemo.class, PrivateFinal.class, PrivateFinalOverload.class})\npublic class CaptorAnnotationTest {\n\n    @Captor\n    private ArgumentCaptor<String> captor;\n\n    @Test\n    public void captorAnnotationWorks() throws Exception {\n        final String expected = \"testing\";\n        FinalDemo demo = mock(FinalDemo.class);\n        demo.say(expected);\n\n        verify(demo).say(captor.capture());\n        assertEquals(expected, captor.getValue());\n    }\n\n    @Test\n    public void captorAnnotationWorksOnPrivateMethods() throws Exception {\n        final String expected = \"testing\";\n        PrivateFinal demo = spy(new PrivateFinal());\n        demo.say(expected);\n\n        verifyPrivate(demo).invoke(\"sayIt\", captor.capture());\n        assertEquals(expected, captor.getValue());\n    }\n\n    @Test\n    public void captorAnnotationWorksOnPrivateOverriddenMethods() throws Exception {\n        final String expected = \"testing\";\n        PrivateFinalOverload demo = spy(new PrivateFinalOverload());\n        demo.say(expected);\n\n        verifyPrivate(demo).invoke(method(PrivateFinalOverload.class, \"say\", String.class, String.class)).withArguments(anyString(), captor.capture());\n        assertEquals(expected, captor.getValue());\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/ChunkingAndStaticInitializerRemovalTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.staticinitializer.SimpleStaticInitializerExample;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.Mockito.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito and PowerMock\n * annotations.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SimpleStaticInitializerExample.class)\npublic class ChunkingAndStaticInitializerRemovalTest {\n\n\t@Mock\n\tprivate SimpleStaticInitializerExample tested;\n\n\t@Test\n\tpublic void testMockingWithNoChunking() throws Exception {\n\t\tfinal String argument = \"hello\";\n\t\tfinal String string = tested.getString();\n\t\tassertEquals(Whitebox.getInternalState(SimpleStaticInitializerExample.class, String.class), string);\n\t\tassertNull(tested.getConcatenatedString(argument));\n\n\t\tverify(tested).getConcatenatedString(argument);\n\t}\n\n\t@SuppressStaticInitializationFor(\"samples.staticinitializer.SimpleStaticInitializerExample\")\n\t@Test\n\tpublic void testMockingWithChunking() throws Exception {\n\t\tfinal String argument = \"hello\";\n\t\tassertNull(tested.getString());\n\t\tassertNull(tested.getConcatenatedString(argument));\n\n\t\tverify(tested).getConcatenatedString(argument);\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/InjectMocksAnnotationTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\nimport samples.injectmocks.DependencyHolder;\n\nimport static org.hamcrest.CoreMatchers.containsString;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.fail;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\n/**\n * Asserts that {@link @InjectMocks} with PowerMock.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class InjectMocksAnnotationTest {\n\n\t@SuppressWarnings(\"unused\")\n\t@Mock\n\tprivate FinalDemo finalDemo;\n\n\t@InjectMocks\n\tprivate DependencyHolder dependencyHolder = new DependencyHolder();\n\n\t@Test\n\tpublic void injectMocksWorks() {\n\t\tassertNotNull(dependencyHolder.getFinalDemo());\n\t}\n\n\t@Test\n\tpublic void testSay() throws Exception {\n\n\t\tFinalDemo tested = dependencyHolder.getFinalDemo();\n\n\t\tString expected = \"Hello altered World\";\n\t\twhen(tested.say(\"hello\")).thenReturn(\"Hello altered World\");\n\n\t\tString actual = tested.say(\"hello\");\n\n\t\tassertEquals(\"Expected and actual did not match\", expected, actual);\n\n\t\t// Should still be mocked by now.\n\t\ttry {\n\t\t\tverify(tested).say(\"world\");\n\t\t\tfail(\"Should throw AssertionError!\");\n\t\t} catch (AssertionError e) {\n\t\t\tassertThat(e.getMessage(), is(containsString(\"Argument(s) are different! Wanted\")));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.Mockito.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito and PowerMock\n * annotations.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class MockFinalUsingAnnotationsTest {\n\n\t@Mock\n\tprivate FinalDemo usingMockitoMockAnnotation;\n\n\t@SuppressWarnings(\"deprecation\")\n\t@org.mockito.Mock\n\tprivate FinalDemo usingDeprecatedMockitoMockAnnotation;\n\n\t@Test\n\tpublic void assertMockFinalWithMockitoMockAnnotationWorks() throws Exception {\n\t\tfinal String argument = \"hello\";\n\n\t\tassertNull(usingMockitoMockAnnotation.say(argument));\n\n\t\tverify(usingMockitoMockAnnotation).say(argument);\n\t}\n\n\t@Test\n\tpublic void assertMockFinalWithDeprecatedMockitoMockAnnotationWorks() throws Exception {\n\t\tfinal String argument = \"hello\";\n\n\t\tassertNull(usingDeprecatedMockitoMockAnnotation.say(argument));\n\n\t\tverify(usingDeprecatedMockitoMockAnnotation).say(argument);\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsWithAnswersTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Answers;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito and PowerMock\n * annotations using answers.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(FinalDemo.class)\npublic class MockFinalUsingAnnotationsWithAnswersTest {\n\n\t@Mock(answer = Answers.RETURNS_DEEP_STUBS)\n\tprivate FinalDemo tested1;\n\n    @Mock(answer = Answers.RETURNS_MOCKS)\n\tprivate FinalDemo tested2;\n\n    @Mock(answer = Answers.RETURNS_MOCKS, name = \"myTested3\")\n\tprivate FinalDemo tested3;\n\n\t@Test public void\n    assert_mock_final_with_mockito_mock_annotation_with_deep_stubs_works() {\n        when(tested1.simpleReturnExample().mySimpleMethod()).thenReturn(42);\n\n        assertEquals(42, tested1.simpleReturnExample().mySimpleMethod());\n\t}\n\n    @Test public void\n    assert_mock_final_with_mockito_mock_annotation_with_returns_mocks_works() {\n\t\tassertNotNull(tested2.simpleReturnExample());\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/SpyAnnotationTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.annotationbased;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Spy;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.partialmocking.PrivatePartialMockingExample;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.verifyPrivate;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n/**\n * Asserts that spying on private methods work with PowerMock when using\n * {@link Spy} annotation.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PrivatePartialMockingExample.class)\npublic class SpyAnnotationTest {\n\n\t@Spy\n\tprivate PrivatePartialMockingExample underTest = new PrivatePartialMockingExample();\n\n\t@Test\n\tpublic void spyingOnPrivateMethodsWorksWithSpyAnnotation() throws Exception {\n\t\tfinal String expected = \"TEST VALUE\";\n\t\tfinal String nameOfMethodToMock = \"methodToMock\";\n\t\tfinal String input = \"input\";\n\t\twhen(underTest, nameOfMethodToMock, input).thenReturn(expected);\n\n\t\tassertEquals(expected, underTest.methodToTest());\n\n\t\tverifyPrivate(underTest).invoke(nameOfMethodToMock, input);\n\t}\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/argumentmatcher/ArgumentMatcherTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.argumentmatcher;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.argumentmatcher.ArgumentMatcherDemo;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertTrue;\nimport static org.mockito.ArgumentMatchers.anyList;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.powermock.api.mockito.PowerMockito.doReturn;\nimport static org.powermock.api.mockito.PowerMockito.mock;\n\n@RunWith(PowerMockRunner.class)\npublic class ArgumentMatcherTest {\n\n    @Test\n    public void worksWithArgumentMatchers() throws Exception {\n        final ArrayList<String> strings = new ArrayList<String>();\n\n        final ArgumentMatcherDemo tested = mock(ArgumentMatcherDemo.class);\n        doReturn(strings).when(tested, \"findByNamedQuery\", eq(\"AbstractPTVTicket.ticketSeatIds\"), anyList());\n\n        final List<String> stringList = tested.findByNamedQuery(\"something\", strings);\n        assertTrue(stringList.isEmpty());\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/ClassLoaderBugTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.bugs;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Enumeration;\n\nimport static org.junit.Assert.assertEquals;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(TestClass.class)\npublic class ClassLoaderBugTest {\n\n    /**\n     * See issue <a href=\"https://code.google.com/p/powermock/issues/detail?id=426\">426</a> for more details.\n     */\n    @Test(timeout = 2000)\n    public void resourcesAreNotLoadedTwice() throws IOException {\n    \tString resourceName = getClass().getCanonicalName().replace(\".\", \"/\") + \".class\";\n        Enumeration<URL> enumeration = getClass().getClassLoader().getResources(resourceName);\n\n        int count = 0;\n        while (enumeration.hasMoreElements()) {\n            System.out.println(enumeration.nextElement().toString());\n            count++;\n        }\n\n        assertEquals(1, count);\n    }\n\n}\n\nclass TestClass {\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github510/package-info.java",
    "content": "/**\n * https://github.com/jayway/powermock/issues/510\n */\npackage samples.powermockito.junit4.bugs.github510;"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/ChildClass.java",
    "content": "package samples.powermockito.junit4.bugs.github583;\n\n/**\n *\n */\npublic class ChildClass extends ParenClass {\n    private int b;\n    public ChildClass() {\n        super();\n    }\n    public int getB() {\n        return b;\n    }\n    public void setB(int b) {\n        this.b = b;\n    }\n    public void test(){\n\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/ClassWithInheritanceTest.java",
    "content": "package samples.powermockito.junit4.bugs.github583;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Spy;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n/**\n *\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(value = {ChildClass.class})\npublic class ClassWithInheritanceTest {\n    @Spy\n    ChildClass b = new ChildClass();\n\n    @Test\n    public void test_test(){\n        b.test();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/ParenClass.java",
    "content": "package samples.powermockito.junit4.bugs.github583;\n\n/**\n *\n */\npublic class ParenClass {\n    private int a;\n    public int getA() {\n        return a;\n    }\n    public void setA(int a) {\n        this.a = a;\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/package-info.java",
    "content": "/**\n * https://github.com/jayway/powermock/issues/583\n */\npackage samples.powermockito.junit4.bugs.github583;"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/GitHub668Test.java",
    "content": "package samples.powermockito.junit4.bugs.github668;\n\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport javax.security.auth.Subject;\n\nimport java.util.HashSet;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(Subject.class)\npublic class GitHub668Test {\n\n    @Test\n    public void shouldMockJavaxSystemFinalClasses() {\n        Subject subject = mock(Subject.class);\n\n        final HashSet<Object> value = new HashSet<Object>();\n        when(subject.getPrivateCredentials()).thenReturn(value);\n\n        assertThat(subject.getPrivateCredentials()).isSameAs(value);\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/package-info.java",
    "content": "/**\n * https://github.com/jayway/powermock/issues/688\n */\npackage samples.powermockito.junit4.bugs.github668;"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/GitHub701Test.java",
    "content": "package samples.powermockito.junit4.bugs.github701;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.doReturn;\nimport static org.powermock.api.mockito.PowerMockito.mock;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({MapWrapper.class})\npublic class GitHub701Test {\n\n    private MapWrapper mocked;\n\n    @Before\n    public void setUp() throws Exception {\n        mocked = mock(MapWrapper.class);\n    }\n\n    @Test\n    public void shouldMockObjectAndReturnRequiredResult() throws Exception {\n\n        doReturn(\"1234\").when(mocked).get(\"numbers\");\n\n        assertThat(mocked.get(\"numbers\")).isEqualTo(\"1234\");\n    }\n\n    @Test\n    public void shouldMockEqualsMethod() {\n\n        assertThat(mocked.equals(mocked)).isEqualTo(true);\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/MapWrapper.java",
    "content": "package samples.powermockito.junit4.bugs.github701;\n\nimport java.io.Serializable;\nimport java.util.Collections;\nimport java.util.Map;\n\npublic final class MapWrapper extends OverridesEquals {\n    private final Map<String, Serializable> data;\n\n    public MapWrapper() {\n        this(Collections.<String, Serializable>emptyMap());\n    }\n\n    MapWrapper(final Map<String, Serializable> data) {\n        this.data = Collections.unmodifiableMap(data);\n    }\n\n    public Object get(final String key) {\n        if (key == null || key.isEmpty()) {\n            return null;\n        }\n        return data.get(key);\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/OverridesEquals.java",
    "content": "package samples.powermockito.junit4.bugs.github701;\n\nabstract class OverridesEquals {\n    @Override\n    public boolean equals (final Object other) {\n        return this == other;\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/package-info.java",
    "content": "/**\n * StackOverflowError mocking final class extending non-public abstract class\n * overriding equals method\n * https://github.com/jayway/powermock/issues/701\n */\npackage samples.powermockito.junit4.bugs.github701;"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/PrepareForTestSignedTest.java",
    "content": "package samples.powermockito.junit4.bugs.github704;\n\nimport org.eclipse.core.runtime.FileLocator;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({SomeClassUseSignedClasses.class, FileLocator.class})\npublic class PrepareForTestSignedTest {\n\n    @Test\n    public void shouldBeAbleMockSignedClasses(){\n        FileLocator fileLocator = mock(FileLocator.class);\n\n        mockStatic(SomeClassUseSignedClasses.class);\n\n        when(SomeClassUseSignedClasses.getFileLocator()).thenReturn(fileLocator);\n\n        assertThat(SomeClassUseSignedClasses.getFileLocator()).isNotNull();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/SomeClassUseSignedClasses.java",
    "content": "package samples.powermockito.junit4.bugs.github704;\n\nimport org.eclipse.core.runtime.FileLocator;\n\npublic class SomeClassUseSignedClasses {\n\n    public static FileLocator getFileLocator(){\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/package-info.java",
    "content": "/**\n * PowerMockito 1.6.5 throws java.lang.SecurityException signer information mismatch if in the PrepareForTest annotation affects also classes which have signatures\n * https://github.com/jayway/powermock/issues/704\n */\npackage samples.powermockito.junit4.bugs.github704;"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/A.java",
    "content": "package samples.powermockito.junit4.bugs.github716;\n\npublic class A {\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/B.java",
    "content": "package samples.powermockito.junit4.bugs.github716;\n\npublic class B {\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/C.java",
    "content": "package samples.powermockito.junit4.bugs.github716;\n\npublic class C {\n\tA a;\n\tB b;\n\tpublic C(A a, B b) {\n\t\tthis.a = a;\n\t\tthis.b = b;\n\t}\n\tpublic int multiply() { return 42; }\n\tpublic A getA() { return a; }\n\tpublic B getB() { return b; }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/MyService.java",
    "content": "package samples.powermockito.junit4.bugs.github716;\n\npublic class MyService {\n\tpublic int doSomething(A a, B b) {\n\t\tC c = new C(a, b);\n\t\treturn c.multiply();\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/WhenNewWithAnyArgumentsTest.java",
    "content": "package samples.powermockito.junit4.bugs.github716;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.hamcrest.core.Is.is;\nimport static org.junit.Assert.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.mockito.PowerMockito.whenNew;\n\n@PrepareForTest({MyService.class})\n@RunWith(PowerMockRunner.class)\npublic class WhenNewWithAnyArgumentsTest {\n\n    @Mock\n    private C c;\n\n    @InjectMocks\n    private MyService cut;\n\n    @Test\n    public void shouldStubNewConstructorCallIfOneOfActualParameterIsNull() throws Exception {\n        A a = new A();\n\n        whenNew(C.class).withAnyArguments().thenReturn(c);\n        when(c.multiply()).thenReturn(42);\n\n        int result = cut.doSomething(a, null);\n        assertThat(result, is(42));\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/package-info.java",
    "content": "/**\n * Powermockito: withAnyArguments\n * when moving from version 1.6.5 to 1.6.6 all tests fail which are using the withAnyArguments inside\n * of \"whenNew\". Proxy objects aren't created any more and stay null which results in NullPointerException\n * https://github.com/jayway/powermock/issues/716\n */\npackage samples.powermockito.junit4.bugs.github716;"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/MockingInterfacesTest.java",
    "content": "package samples.powermockito.junit4.bugs.github731;\n\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.util.concurrent.ExecutionException;\n\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n@RunWith(PowerMockRunner.class)\npublic class MockingInterfacesTest {\n    \n    @Test\n    public void should_stub_future_get_method() throws ExecutionException, InterruptedException {\n        \n        SomeInterface<OptionalInterface<AType>> mockFuture = mock(SomeInterface.class);\n        \n        OptionalInterface<AType> mockTypeOpt = mock(OptionalInterface.class);\n        \n        when(mockFuture.get()).thenReturn(mockTypeOpt);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/SomeException.java",
    "content": "package samples.powermockito.junit4.bugs.github731;\n\npublic class SomeException extends Exception{\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/EqualsStatic.java",
    "content": "package samples.powermockito.junit4.bugs.github781;\n\npublic class EqualsStatic {\n    public static boolean equals() {\n        return false;\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/GitHub781Test.java",
    "content": "package samples.powermockito.junit4.bugs.github781;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.mockito.Mockito.spy;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(EqualsStatic.class)\npublic class GitHub781Test {\n\n    private SpyObject partialMock = null;\n    private final boolean result = true;\n\n    @Test\n    public void testCallMockStaticEquals() {\n        PowerMockito.mockStatic(EqualsStatic.class);\n        PowerMockito.when(EqualsStatic.equals()).thenReturn(result);\n        partialMock = spy(new SpyObject());\n\n        assertThat(partialMock.callEquals()).isEqualTo(result);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/SpyObject.java",
    "content": "package samples.powermockito.junit4.bugs.github781;\n\npublic class SpyObject {\n    public boolean callEquals() {\n        return EqualsStatic.equals();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnoreTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.bugs.github801;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\n@RunWith(PowerMockRunner.class)\npublic class GlobalPowerMockIgnoreTest {\n    \n    @Test\n    public void should_load_class_from_global_ignore_with_system_class_loader() {\n        GlobalPowerMockIgnore globalPowerMockIgnore = new GlobalPowerMockIgnore();\n        \n        assertThat(globalPowerMockIgnore.getClass().getClassLoader())\n            .as(\"Class is loaded by System Classloader\")\n            .isSameAs(ClassLoader.getSystemClassLoader());\n    }\n    \n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github806/DoThrowTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.bugs.github806;\n\nimport org.junit.Test;\nimport org.mockito.Mockito;\n\nimport static org.mockito.Mockito.doThrow;\n\npublic class DoThrowTest {\n    \n    @Test(expected = RuntimeException.class)\n    public void should_throw_expected_exception() {\n        final DoThrowTMockClass mock = Mockito.mock(DoThrowTMockClass.class);\n        doThrow(RuntimeException.class).when(mock).doSomething();\n        mock.doSomething();\n    }\n    \n    @Test(expected = CustomException.class)\n    public void should_throw_custom_exception() throws CustomException {\n        new DoThrowTMockClass().throwExceptionForInput(\"123\");\n    }\n    \n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github806/package-info.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\n/**\n * Exception verification in junit tests #806\n * <p>\n * <code>\n * @Test(expected = NotFoundException.class)\n * public void a() {\n * doThrow(NotFoundException.class).when(b).doSomething();\n * b.doSomething();\n * }\n * </code>\n * Test failure, throws RuntimeExceptionProxy instead of NotFoundException\n * <p>\n * https://github.com/powermock/powermock/issues/806\n */\npackage samples.powermockito.junit4.bugs.github806;"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/constructor/InnerConstructorsAreFoundTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.constructor;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.powermock.api.mockito.PowerMockito.whenNew;\n\n/**\n * Asserts that <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=267\">issue 267</a>\n * is resolved.\n */\n@PrepareForTest({ InnerConstructorsAreFoundTest.WorkingObjectUnderTesting.class,\n\t\tInnerConstructorsAreFoundTest.BuggyObjectUnderTesting.class,\n\t\tInnerConstructorsAreFoundTest.StillBuggyObjectUnderTesting.class })\n@RunWith(PowerMockRunner.class)\npublic class InnerConstructorsAreFoundTest {\n\n\tinterface AnyInterface {\n\t};\n\n\tclass AnyImplementation implements AnyInterface {\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tclass SomeOtherImplementationOfSomethingElse {\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\treturn true;\n\t\t}\n\t};\n\n\t// <ObjectsUnderTesting>\n\tclass WorkingObjectUnderTesting {\n\t\tvoid methodToTest() {\n\t\t\tnew WorkingObjectToMock(new AnyImplementation());\n\t\t}\n\t}\n\n\tclass BuggyObjectUnderTesting {\n\t\tvoid methodToTest() {\n\t\t\tnew BuggyObjectToMock(new SomeOtherImplementationOfSomethingElse(), new AnyImplementation());\n\t\t}\n\t}\n\n\tclass StillBuggyObjectUnderTesting {\n\t\tvoid methodToTest() {\n\t\t\tnew StillBuggyObjectToMock(new SomeOtherImplementationOfSomethingElse(),\n\t\t\t\t\tnew AnyInterface[] { new AnyImplementation() });\n\t\t}\n\t}\n\n\t// </ObjectsUnderTesting>\n\n\t// <ObjectsToMock>\n\tclass WorkingObjectToMock {\n\t\tpublic WorkingObjectToMock(AnyInterface... anys) {\n\t\t}\n\t}\n\n\tclass BuggyObjectToMock {\n\t\t@SuppressWarnings(\"unused\")\n\t\tprivate final AnyInterface[] anys;\n\n\t\tpublic BuggyObjectToMock(SomeOtherImplementationOfSomethingElse other, AnyInterface... anys) {\n\t\t\tthis.anys = anys;\n\t\t}\n\t}\n\n\tclass StillBuggyObjectToMock {\n\t\t@SuppressWarnings(\"unused\")\n\t\tprivate final AnyInterface[] anys;\n\n\t\tpublic StillBuggyObjectToMock(SomeOtherImplementationOfSomethingElse other, AnyInterface[] anys) {\n\t\t\tthis.anys = anys;\n\t\t}\n\t}\n\n\t@Mock\n\tWorkingObjectToMock mockedWorkingObject;\n\t@Mock\n\tBuggyObjectToMock mockedBuggyObject;\n\t@Mock\n\tStillBuggyObjectToMock mockedStillBuggyObject;\n\n\t@Test\n\tpublic void shouldFindMemberVarArgsCtorWhenPassingArrayToWithArguments() throws Exception {\n\t\twhenNew(BuggyObjectToMock.class).withArguments(new SomeOtherImplementationOfSomethingElse(),\n\t\t\t\t(Object[]) new AnyInterface[] { new AnyImplementation() }).thenReturn(mockedBuggyObject);\n\n\t\tnew BuggyObjectUnderTesting().methodToTest();\n\t}\n\n\t@Test\n\tpublic void shouldFindMemberArrayCtorWhenPassingArrayToWithArguments() throws Exception {\n\t\twhenNew(StillBuggyObjectToMock.class).withArguments(new SomeOtherImplementationOfSomethingElse(),\n\t\t\t\t(Object) new AnyInterface[] { new AnyImplementation() }).thenReturn(mockedStillBuggyObject);\n\n\t\tnew StillBuggyObjectUnderTesting().methodToTest();\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/doreturn/DoReturnTest.java",
    "content": "package samples.powermockito.junit4.doreturn;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.core.Is.is;\nimport static org.hamcrest.core.IsEqual.equalTo;\nimport static org.powermock.api.mockito.PowerMockito.doReturn;\n\n/**\n * Created by gauee on 12/11/15.\n * Test that demonstrates that <a\n * href=\"https://github.com/jayway/powermock/issues/599\">issue 599</a>\n * is resolved.\n */\n@RunWith(PowerMockRunner.class)\npublic class DoReturnTest {\n\n    private static final String TEMP_DAY_FIRST = \"41F\";\n    private static final String TEMP_DAY_SECOND = \"44F\";\n\n    @Mock\n    private Weather weather;\n\n    interface Weather {\n        String getTemperature();\n    }\n\n    @Before\n    public void init() {\n        doReturn(TEMP_DAY_FIRST, TEMP_DAY_SECOND).when(weather).getTemperature();\n    }\n\n    @Test\n    public void returnsDifferentTemperatureForEachInvocation(){\n        assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_FIRST)));\n        assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_SECOND)));\n    }\n\n    @Test\n    public void returnsFirstTemperatureWhenPassedArrayIsEmpty() {\n        doReturn(TEMP_DAY_FIRST, new Object[0]).when(weather).getTemperature();\n\n        assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_FIRST)));\n        assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_FIRST)));\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/enums/EnumWithConstructorTest.java",
    "content": "package samples.powermockito.junit4.enums;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.enummocking.EnumWithConstructor;\nimport samples.enummocking.SomeObjectInterfaceImpl;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.sameInstance;\nimport static org.junit.Assert.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.whenNew;\n\n/**\n *\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(value = {EnumWithConstructor.class, SomeObjectInterfaceImpl.class}, fullyQualifiedNames = \"samples.enummocking.EnumWithConstructor$1\")\npublic class EnumWithConstructorTest {\n\n    @Mock(name = \"expectedSomeObjectInterfaceImpl\")\n    private SomeObjectInterfaceImpl someImplMock;\n\n    @Test\n    public void testCallMethodWithConstructor() throws Exception {\n\n        whenNew(SomeObjectInterfaceImpl.class).withNoArguments().thenReturn(someImplMock);\n\n        SomeObjectInterfaceImpl actual = (SomeObjectInterfaceImpl) EnumWithConstructor.SOME_ENUM_VALUE.create();\n\n        assertThat(actual, is(sameInstance(someImplMock)));\n\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/equalsmocking/EqualsMockingTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.equalsmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport javax.naming.InitialContext;\n\nimport static org.junit.Assert.assertTrue;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.stub;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(InitialContext.class)\npublic class EqualsMockingTest {\n\n    @Test\n    public void shouldStubEquals() throws Exception {\n        stub(method(InitialContext.class, \"equals\")).toReturn(true);\n        final InitialContext context = new InitialContext();\n\n        assertTrue(context.equals(new Object()));\n    }\n    \n    @Test\n    public void shouldMockEquals() throws Exception {\n        Object object = new Object();\n        \n        final InitialContext context = mock(InitialContext.class);\n        when(context.equals(object)).thenReturn(true);\n\n        assertTrue(context.equals(object));\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalMethodsCases.java",
    "content": "package samples.powermockito.junit4.finalmocking;\n\nimport org.junit.Test;\nimport samples.finalmocking.FinalDemo;\nimport samples.privateandfinal.PrivateFinal;\n\nimport java.lang.reflect.Method;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.doThrow;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.spy;\nimport static org.powermock.api.mockito.PowerMockito.verifyPrivate;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\n\n/**\n * Cases to check mocking final non-static methods and final class\n */\npublic class MockFinalMethodsCases {\n    @Test\n    public void shouldMockFinalMethodWithNoExpectations() throws Exception {\n        final String argument = \"hello\";\n\n        FinalDemo tested = mock(FinalDemo.class);\n\n        assertThat(tested.say(argument)).isNull();\n\n        verify(tested).say(argument);\n    }\n\n    @Test\n    public void shouldMockFinalMethodWithExpectations() throws Exception {\n        final String argument = \"hello\";\n        final String expected = \"Hello altered World\";\n\n        FinalDemo tested = mock(FinalDemo.class);\n\n        when(tested.say(argument)).thenReturn(expected);\n\n        final String actual = tested.say(argument);\n\n        verify(tested).say(argument);\n\n        assertThat(actual).isEqualTo(expected);\n    }\n\n    @Test\n    public void shouldMockFinalNativeMethodWithExpectations() throws Exception {\n        final String expected = \"Hello altered World\";\n        final String argument = \"hello\";\n\n        FinalDemo tested = mock(FinalDemo.class);\n\n        when(tested.sayFinalNative(argument)).thenReturn(\"Hello altered World\");\n\n        String actual = tested.sayFinalNative(argument);\n\n        verify(tested).sayFinalNative(argument);\n        assertThat(actual).isEqualTo(expected);\n    }\n\n    @Test\n    public void shouldSpyingOnFinalInstanceMethod() throws Exception {\n        FinalDemo tested = new FinalDemo();\n        FinalDemo spy = spy(tested);\n\n        final String argument = \"PowerMock\";\n        final String expected = \"something\";\n\n        assertThat(spy.say(argument)).isEqualTo(\"Hello \" + argument);\n\n        when(spy.say(argument)).thenReturn(expected);\n\n        assertThat(spy.say(argument)).isEqualTo(expected);\n    }\n\n    @Test(expected = ArrayStoreException.class)\n    public void shouldSpyingOnFinalVoidInstanceMethod() throws Exception {\n        FinalDemo tested = new FinalDemo();\n        FinalDemo spy = spy(tested);\n\n        doThrow(new ArrayStoreException()).when(spy).finalVoidCallee();\n\n        spy.finalVoidCaller();\n    }\n\n    @Test\n    public void shouldSpyingOnPrivateFinalInstanceMethod() throws Exception {\n        PrivateFinal spy = spy(new PrivateFinal());\n\n        final String expected = \"test\";\n\n        assertThat(spy.say(expected)).isEqualTo(\"Hello \" + expected);\n\n        when(spy, \"sayIt\", isA(String.class)).thenReturn(expected);\n\n        assertThat(spy.say(expected)).isEqualTo(expected);\n\n        verifyPrivate(spy, times(2)).invoke(\"sayIt\", expected);\n    }\n\n    @Test\n    public void shouldSpyingOnPrivateFinalInstanceMethodWhenUsingJavaLangReflectMethod() throws Exception {\n        PrivateFinal spy = spy(new PrivateFinal());\n\n        final String expected = \"test\";\n        assertThat(spy.say(expected)).isEqualTo(\"Hello \" + expected);\n\n        final Method methodToExpect = method(PrivateFinal.class, \"sayIt\");\n        when(spy, methodToExpect).withArguments(isA(String.class)).thenReturn(expected);\n\n        assertThat(spy.say(expected)).isEqualTo(expected);\n\n        verifyPrivate(spy, times(2)).invoke(methodToExpect).withArguments(expected);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalNonStaticMethodsTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.finalmocking;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\nimport samples.privateandfinal.PrivateFinal;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({FinalDemo.class, PrivateFinal.class})\npublic class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases {\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getannotation/GetAnnotationTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.getannotation;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.annotationbased.AnnotatedClassDemo;\nimport samples.annotationbased.testannotations.RuntimeAnnotation;\n\nimport static org.junit.Assert.*;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n/**\n * Assert that \"isAnnotationPresent\" and \"getAnnotation\" works correctly when mockStatic is used\n * @see <a href=\"https://github.com/jayway/powermock/issues/676\">Issue 676</a>\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(AnnotatedClassDemo.class)\npublic class GetAnnotationTest {\n\n    @Before\n    public void setUp() {\n        mockStatic(AnnotatedClassDemo.class);\n        when(AnnotatedClassDemo.staticMethod()).thenReturn(true);\n    }\n\n    @Test\n    public void getClassAnnotationsReturnActualAnnotationsByDefault() throws Exception {\n        assertTrue(AnnotatedClassDemo.class.isAnnotationPresent(RuntimeAnnotation.class));\n        assertNotNull(AnnotatedClassDemo.class.getAnnotation(RuntimeAnnotation.class));\n        assertTrue(AnnotatedClassDemo.staticMethod());\n    }\n\n    @Test\n    public void nonExistingAnnotationsAreNotReturnedByDefault() throws Exception {\n        assertFalse(AnnotatedClassDemo.class.isAnnotationPresent(Deprecated.class));\n        assertNull(AnnotatedClassDemo.class.getAnnotation(Deprecated.class));\n        assertTrue(AnnotatedClassDemo.staticMethod());\n    }\n\n    // behavior before the fix:\n    \n    @Test\n    public void isAnnotationPresentReturnsFalseWhenMethodsAreMocked() throws Exception {\n        MockGateway.MOCK_ANNOTATION_METHODS = true;\n        try {\n            assertFalse(AnnotatedClassDemo.class.isAnnotationPresent(RuntimeAnnotation.class));\n            assertTrue(AnnotatedClassDemo.staticMethod());\n        } finally {\n            MockGateway.MOCK_ANNOTATION_METHODS = false;\n        }\n    }\n\n    @Test\n    public void getAnnotationReturnsNullWhenMethodsAreMocked() throws Exception {\n        MockGateway.MOCK_ANNOTATION_METHODS = true;\n        try {\n            assertNull(AnnotatedClassDemo.class.getAnnotation(RuntimeAnnotation.class));\n            assertTrue(AnnotatedClassDemo.staticMethod());\n        } finally {\n            MockGateway.MOCK_ANNOTATION_METHODS = false;\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getclass/GetClassTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.getclass;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.MockGateway;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\n\nimport static org.junit.Assert.*;\nimport static org.powermock.api.mockito.PowerMockito.mock;\n\n/**\n * Assert that \"getClass\" on an object works correctly on objects\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ExpectNewDemo.class)\npublic class GetClassTest {\n\n    @Test\n    public void getClassReturnsTheCorrectClassForNewInstancesOfClassesPrepareForTest() throws Exception {\n        ExpectNewDemo instance = new ExpectNewDemo();\n        assertEquals(ExpectNewDemo.class, instance.getClass());\n    }\n\n    @Test\n    public void getClassReturnsTheCorrectClassForMocksPrepareForTest() throws Exception {\n        ExpectNewDemo instance = mock(ExpectNewDemo.class);\n        assertNotNull(instance.getClass());\n    }\n\n    @Test\n    public void getClassReturnsNullForMocksPreparedForTestWhenMockingOfGetClassAllowed() throws Exception {\n        MockGateway.MOCK_GET_CLASS_METHOD = true;\n        ExpectNewDemo instance = mock(ExpectNewDemo.class);\n        try {\n            assertNull(instance.getClass());\n        } finally {\n            // Make sure we reset to the default for subsequent tests.\n            MockGateway.MOCK_GET_CLASS_METHOD = false;\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/hashcode/HashCodeTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.hashcode;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport javax.naming.InitialContext;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.stub;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(InitialContext.class)\npublic class HashCodeTest {\n    private final static int EXPECTED_HASH = 12316;\n\n    @Test\n    public void shouldStubHashCode() throws Exception {\n        stub(method(InitialContext.class, \"hashCode\")).toReturn(EXPECTED_HASH);\n        final InitialContext context = new InitialContext();\n\n        assertEquals(EXPECTED_HASH, context.hashCode());\n    }\n\n    @Test\n    public void shouldMockHashCode() throws Exception {\n        InitialContext context = mock(InitialContext.class);\n        when(context.hashCode()).thenReturn(EXPECTED_HASH);\n\n        assertEquals(EXPECTED_HASH, context.hashCode());\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/hashcode/InnerClassHashCodeTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.hashcode;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.util.HashMap;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.stub;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({InnerClassHashCodeTest.SubHashMap.class})\npublic class InnerClassHashCodeTest {\n\n    private static final int EXPECTED_HASH = 123456;\n\n    @Test\n    @Ignore(\"This should work but it's a bug\")\n    public void can_mock_inner_hash_code_method() {\n        SubHashMap actor = mock(SubHashMap.class);\n        when(actor.hashCode()).thenReturn(EXPECTED_HASH);\n\n        int hashCode = actor.hashCode();\n\n        assertThat(hashCode, equalTo(EXPECTED_HASH));\n    }\n\n    @Test\n    public void can_stub_inner_hash_code_method() {\n        stub(method(SubHashMap.class, \"hashCode\")).toReturn(EXPECTED_HASH);\n        SubHashMap actor = new SubHashMap();\n\n        int hashCode = actor.hashCode();\n\n        assertThat(hashCode, equalTo(123456));\n    }\n\n    public class SubHashMap extends HashMap {\n        @Override\n        public int hashCode() {\n            return super.hashCode();\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            return super.equals(o);\n        }\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/InstanceMethods.java",
    "content": "package samples.powermockito.junit4.jacoco;\n\nimport java.util.Random;\n\npublic final class InstanceMethods {\n\n    private static final Random random = new Random();\n\n    public int calculateSomething(int in){\n        int r = in;\n        for (int i = 0; i < max(); i++) {\n            r += in * i % getSomeFactor();\n        }\n        return r;\n    }\n\n    private int getSomeFactor() {\n        return random.nextInt(2);\n    }\n\n    private int max() {\n        return random.nextInt(100);\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/JacocoCoverageTest.java",
    "content": "package samples.powermockito.junit4.jacoco;\n\n\nimport org.jacoco.core.analysis.Analyzer;\nimport org.jacoco.core.analysis.CoverageBuilder;\nimport org.jacoco.core.analysis.IClassCoverage;\nimport org.jacoco.core.analysis.IMethodCoverage;\nimport org.jacoco.core.data.ExecutionDataStore;\nimport org.jacoco.core.data.SessionInfoStore;\nimport org.jacoco.core.instr.Instrumenter;\nimport org.jacoco.core.runtime.IRuntime;\nimport org.jacoco.core.runtime.LoggerRuntime;\nimport org.jacoco.core.runtime.RuntimeData;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.JUnitCore;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.URISyntaxException;\nimport java.net.URL;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\npublic class JacocoCoverageTest {\n\n    public static final String[] TARGET = new String[]{\n            TargetTest.class.getName(),\n            StaticMethods.class.getName(),\n            InstanceMethods.class.getName()\n    };\n\n    @Test\n    public void jacocoOfflineInstShouldCalculateCoverageAfterPowerMockTransformation() throws Exception {\n        final RuntimeData data = new RuntimeData();\n\n        runTargetTest(data);\n\n        final CoverageBuilder coverageBuilder = collectCoverage(getExecutionDataStore(data));\n\n        assertCodeCoverage(coverageBuilder);\n    }\n\n    private void runTargetTest(RuntimeData data) throws Exception {IRuntime runtime = new LoggerRuntime();\n        instrumentClasses(runtime);\n\n        runtime.startup(data);\n\n        JUnitCore.runClasses(TargetTest.class);\n\n        runtime.shutdown();\n\n        restoreOriginalClasses();\n    }\n\n    private void assertCodeCoverage(CoverageBuilder coverageBuilder) {\n        for (IClassCoverage classCoverage : coverageBuilder.getClasses()) {\n            for (IMethodCoverage methodCoverage : classCoverage.getMethods()) {\n                if (methodCoverage.getName().equals(\"calculateSomething\")) {\n                    assertThat(methodCoverage.getLineCounter().getCoveredRatio()).isEqualTo(1.0);\n                    assertThat(methodCoverage.getLineCounter().getCoveredCount()).isEqualTo(4);\n                }\n            }\n        }\n    }\n\n    private CoverageBuilder collectCoverage(ExecutionDataStore executionData) throws IOException {\n        final CoverageBuilder coverageBuilder = new CoverageBuilder();\n        final Analyzer analyzer = new Analyzer(executionData, coverageBuilder);\n        for (String className : TARGET) {\n            analyzer.analyzeClass(getClass().getResourceAsStream(classNameToFileName(className)), className);\n        }\n        return coverageBuilder;\n    }\n\n    private ExecutionDataStore getExecutionDataStore(RuntimeData data) {\n        final ExecutionDataStore executionData = new ExecutionDataStore();\n        final SessionInfoStore sessionInfos = new SessionInfoStore();\n        data.collect(executionData, sessionInfos, false);\n        return executionData;\n    }\n\n    private void restoreOriginalClasses() throws URISyntaxException, IOException {\n        for (String className : TARGET) {\n            final String classResource = classNameToFileName(className);\n            URL classResourceURL = getClass().getResource(classResource);\n            File originalFile = new File(classResourceURL.toURI());\n            restoreOriginalFile(originalFile);\n        }\n    }\n\n    private void instrumentClasses(IRuntime runtime) throws URISyntaxException, IOException {\n        Instrumenter instr = new Instrumenter(runtime);\n        for (String className : TARGET) {\n            instrumentClass(instr, className);\n        }\n    }\n\n\n    private static void copyFileUsingStream(File source, File dest) throws IOException {\n        InputStream is = null;\n        OutputStream os = null;\n        try {\n            is = new FileInputStream(source);\n            os = new FileOutputStream(dest, false);\n            byte[] buffer = new byte[1024];\n            int length;\n            while ((length = is.read(buffer)) > 0) {\n                os.write(buffer, 0, length);\n            }\n        } finally {\n            if (is != null) {\n                is.close();\n            }\n            if (os != null) {\n                os.close();\n            }\n        }\n    }\n\n    private void restoreOriginalFile(File originalFile) throws IOException {\n        File backup = new File(originalFile.getAbsolutePath() + \".bak\");\n        if (originalFile.exists()) {\n            originalFile.delete();\n        }\n        copyFileUsingStream(backup, originalFile);\n    }\n\n    private void instrumentClass(Instrumenter instr,\n                                 String className) throws URISyntaxException, IOException {\n        URL classResourceURL = getClass().getResource(classNameToFileName(className));\n        File originalFile = new File(classResourceURL.toURI());\n\n        copyOriginalFile(originalFile);\n\n        final byte[] instrumented = instr.instrument(classResourceURL.openStream(), className);\n\n        writeInstrumentedFile(originalFile, instrumented);\n    }\n\n    private void copyOriginalFile(File originalFile) throws IOException, URISyntaxException {\n        File backup = new File(originalFile.getAbsolutePath() + \".bak\");\n        if (backup.exists()) {\n            backup.delete();\n        }\n        copyFileUsingStream(originalFile, backup);\n    }\n\n    private void writeInstrumentedFile(File originalFile, byte[] instrumented) throws IOException {\n        FileOutputStream fooStream = null;\n        try {\n            fooStream = new FileOutputStream(originalFile, false);\n            fooStream.write(instrumented);\n        } finally {\n            if (fooStream != null) {\n                fooStream.close();\n            }\n        }\n    }\n\n\n    private String classNameToFileName(String name) {return '/' + name.replace('.', '/') + \".class\";}\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/StaticMethods.java",
    "content": "package samples.powermockito.junit4.jacoco;\n\nimport java.util.Random;\n\npublic class StaticMethods {\n\n    private static final Random RANDOM = new Random();\n\n    public static int calculateSomething(int in){\n        int r = in;\n        for (int i = 0; i < max(); i++) {\n            r += in * i % getSomeFactor();\n        }\n        return r;\n    }\n\n    private static int getSomeFactor() {\n        return RANDOM.nextInt(2);\n    }\n\n    private static int max() {\n        return RANDOM.nextInt(100);\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/TargetTest.java",
    "content": "package samples.powermockito.junit4.jacoco;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.doReturn;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({StaticMethods.class, InstanceMethods.class})\npublic class TargetTest {\n\n    @Test\n    public void shouldCalculateSomethingStatic() throws Exception {\n        mockStatic(StaticMethods.class);\n\n        doReturn(1).when(StaticMethods.class, \"getSomeFactor\");\n        doReturn(1).when(StaticMethods.class, \"max\");\n\n        when(StaticMethods.calculateSomething(10)).thenCallRealMethod();\n\n        assertThat(StaticMethods.calculateSomething(10)).isEqualTo(10);\n    }\n\n    @Test\n    public void shouldCalculateSomething() throws Exception {\n\n        InstanceMethods instanceMethods = mock(InstanceMethods.class);\n\n        doReturn(1).when(instanceMethods, \"getSomeFactor\");\n        doReturn(1).when(instanceMethods, \"max\");\n\n        when(instanceMethods.calculateSomething(10)).thenCallRealMethod();\n\n        assertThat(instanceMethods.calculateSomething(10)).isEqualTo(10);\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/largemethod/LargeMethodTest.java",
    "content": "package samples.powermockito.junit4.largemethod;\r\n\r\nimport org.junit.Test;\r\nimport org.junit.runner.RunWith;\r\nimport org.powermock.api.mockito.PowerMockito;\r\nimport org.powermock.core.classloader.annotations.PrepareForTest;\r\nimport org.powermock.modules.junit4.PowerMockRunner;\r\nimport samples.largemethod.MethodExceedingJvmLimit;\r\n\r\nimport static junit.framework.Assert.assertEquals;\r\nimport static junit.framework.Assert.assertNull;\r\nimport static junit.framework.Assert.assertSame;\r\nimport static junit.framework.Assert.assertTrue;\r\nimport static junit.framework.Assert.fail;\r\nimport static org.mockito.Mockito.when;\r\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\r\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\r\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\r\n\r\n@RunWith(PowerMockRunner.class)\r\n@PrepareForTest(MethodExceedingJvmLimit.class)\r\npublic class LargeMethodTest {\r\n\r\n    @Test\r\n    public void largeMethodShouldBeOverridden() {\r\n        try {\r\n            MethodExceedingJvmLimit.init();\r\n            fail(\"Method should be overridden and exception should be thrown\");\r\n        } catch (Exception e) {\r\n            assertSame(IllegalAccessException.class, e.getClass());\r\n            assertTrue(e.getMessage().contains(\"Method was too large and after instrumentation exceeded JVM limit\"));\r\n        }\r\n    }\r\n\r\n    @Test\r\n    public void largeMethodShouldBeAbleToBeSuppressed() {\r\n        suppress(PowerMockito.method(MethodExceedingJvmLimit.class, \"init\"));\r\n        assertNull(\"Suppressed method should return: null\", MethodExceedingJvmLimit.init());\r\n    }\r\n\r\n    @Test\r\n    public void largeMethodShouldBeAbleToBeMocked() {\r\n        mockStatic(MethodExceedingJvmLimit.class);\r\n        when(MethodExceedingJvmLimit.init()).thenReturn(\"ok\");\r\n        assertEquals(\"Mocked method should return: ok\", \"ok\", MethodExceedingJvmLimit.init());\r\n        verifyStatic(MethodExceedingJvmLimit.class);\r\n        MethodExceedingJvmLimit.init();\r\n    }\r\n\r\n    @Test(expected = IllegalStateException.class)\r\n    public void largeMethodShouldBeAbleToBeMockedAndThrowException() {\r\n        mockStatic(MethodExceedingJvmLimit.class);\r\n        when(MethodExceedingJvmLimit.init()).thenThrow(new IllegalStateException());\r\n        MethodExceedingJvmLimit.init();\r\n        verifyStatic(MethodExceedingJvmLimit.class);\r\n        MethodExceedingJvmLimit.init();\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/membermodification/MemberModificationExampleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.membermodification;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticandinstance.StaticAndInstanceDemo;\nimport samples.suppressconstructor.SuppressConstructorHierarchy;\nimport samples.suppresseverything.SuppressEverything;\nimport samples.suppressfield.SuppressField;\nimport samples.suppressmethod.SuppressMethod;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\nimport static org.hamcrest.CoreMatchers.instanceOf;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.junit.Assert.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructorsDeclaredIn;\nimport static org.powermock.api.support.membermodification.MemberMatcher.everythingDeclaredIn;\nimport static org.powermock.api.support.membermodification.MemberMatcher.field;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberMatcher.methods;\nimport static org.powermock.api.support.membermodification.MemberMatcher.methodsDeclaredIn;\nimport static org.powermock.api.support.membermodification.MemberModifier.*;\n\n/**\n * Demonstrates PowerMock's ability to modify member structures.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { SuppressMethod.class, SuppressField.class, SuppressEverything.class })\npublic class MemberModificationExampleTest {\n\n    @Test\n    public void suppressSingleMethodExample() throws Exception {\n        suppress(method(SuppressMethod.class, \"getObject\"));\n\n        assertNull(new SuppressMethod().getObject());\n    }\n\n    @Test\n    public void suppressMultipleMethodsExample1() throws Exception {\n        suppress(methods(SuppressMethod.class, \"getObject\", \"getInt\"));\n\n        assertNull(new SuppressMethod().getObject());\n        assertEquals(0, new SuppressMethod().getInt());\n    }\n\n    @Test\n    public void suppressMultipleMethodsExample2() throws Exception {\n        suppress(methods(method(SuppressMethod.class, \"getObject\"), method(SuppressMethod.class, \"getInt\")));\n\n        assertNull(new SuppressMethod().getObject());\n        assertEquals(0, new SuppressMethod().getInt());\n    }\n\n    @Test\n    public void suppressAllMethodsExample() throws Exception {\n        suppress(methodsDeclaredIn(SuppressMethod.class));\n\n        final SuppressMethod tested = new SuppressMethod();\n\n        assertNull(tested.getObject());\n        assertNull(SuppressMethod.getObjectStatic());\n        assertEquals(0, tested.getByte());\n    }\n\n    @Test\n    public void suppressSingleFieldExample() throws Exception {\n        suppress(field(SuppressField.class, \"domainObject\"));\n\n        SuppressField tested = new SuppressField();\n        assertNull(tested.getDomainObject());\n    }\n\n    @Test\n    public void suppressConstructorExample() throws Exception {\n        suppress(constructor(SuppressConstructorHierarchy.class));\n\n        SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy(\"message\");\n\n        assertEquals(42, tested.getNumber());\n        assertNull(tested.getMessage());\n    }\n\n    @Test\n    public void stubSingleMethodExample() throws Exception {\n        final String expectedReturnValue = \"new\";\n        stub(method(SuppressMethod.class, \"getObject\")).toReturn(expectedReturnValue);\n\n        final SuppressMethod tested = new SuppressMethod();\n        assertEquals(expectedReturnValue, tested.getObject());\n        assertEquals(expectedReturnValue, tested.getObject());\n    }\n\n    @Test\n    public void duckTypeStaticMethodExample() throws Exception {\n        replace(method(SuppressMethod.class, \"getObjectStatic\")).with(\n                method(StaticAndInstanceDemo.class, \"getStaticMessage\"));\n\n        assertEquals(SuppressMethod.getObjectStatic(), StaticAndInstanceDemo.getStaticMessage());\n    }\n\n    @Test\n    public void whenReplacingMethodWithAMethodOfIncorrectReturnTypeThenAnIAEIsThrown() throws Exception {\n        try {\n            replace(method(SuppressMethod.class, \"getObjectStatic\")).with(\n                    method(StaticAndInstanceDemo.class, \"aVoidMethod\"));\n            fail(\"Should thow IAE\");\n        } catch (Exception e) {\n            assertEquals(\"The replacing method (public static void samples.staticandinstance.StaticAndInstanceDemo.aVoidMethod()) needs to return java.lang.Object and not void.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void whenReplacingMethodWithAMethodOfWithIncorrectParametersThenAnIAEIsThrown() throws Exception {\n        try {\n            replace(method(SuppressMethod.class, \"getObjectStatic\")).with(\n                    method(StaticAndInstanceDemo.class, \"aMethod2\"));\n            fail(\"Should thow IAE\");\n        } catch (Exception e) {\n            assertEquals(\"The replacing method, \\\"public static java.lang.Object samples.staticandinstance.StaticAndInstanceDemo.aMethod2(java.lang.String)\\\", needs to have the same number of parameters of the same type as as method \\\"public static java.lang.Object samples.suppressmethod.SuppressMethod.getObjectStatic()\\\".\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void changingReturnValueExample() throws Exception {\n        replace(method(SuppressMethod.class, \"getObjectWithArgument\")).with(new ReturnValueChangingInvocationHandler());\n\n        final SuppressMethod tested = new SuppressMethod();\n\n        assertThat(tested.getObjectWithArgument(\"don't do anything\"), is(instanceOf(Object.class)));\n        assertEquals(\"hello world\", tested.getObjectWithArgument(\"make it a string\"));\n    }\n\n    @Test\n    public void suppressAllConstructors() throws Exception {\n        suppress(constructorsDeclaredIn(SuppressEverything.class));\n\n        SuppressEverything suppressEverything = new SuppressEverything();\n        new SuppressEverything(\"test\");\n\n        try {\n            suppressEverything.something();\n            fail(\"Should throw ISE\");\n        } catch (IllegalStateException e) {\n            assertEquals(\"error\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void suppressEverythingExample() throws Exception {\n        suppress(everythingDeclaredIn(SuppressEverything.class));\n\n        SuppressEverything suppressEverything = new SuppressEverything();\n        new SuppressEverything(\"test\");\n        suppressEverything.something();\n        suppressEverything.somethingElse();\n    }\n\n    private final class ReturnValueChangingInvocationHandler implements InvocationHandler {\n        @Override\n        public Object invoke(Object object, Method method, Object[] arguments) throws Throwable {\n            if (arguments[0].equals(\"make it a string\")) {\n                return \"hello world\";\n            } else {\n                return method.invoke(object, arguments);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/nested/NestedClassDefinedInsideTestCaseTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.nested;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { NestedClassDefinedInsideTestCaseTest.class })\npublic class NestedClassDefinedInsideTestCaseTest {\n\n    @Test\n    public void mocksNestedPrivateClassDefinedInsideTestCase() throws Exception {\n        NestedPrivateClassDefinedInsideTestCase tested = mock(NestedPrivateClassDefinedInsideTestCase.class);\n        when(tested.getValue()).thenReturn(\"something\");\n\n        assertEquals(\"something\", tested.getValue());\n    }\n\n    @Test\n    @Ignore(\"See issue 95\")\n    public void mocksNestedPrivateFinalClassDefinedInsideTestCase() throws Exception {\n        NestedPrivateFinalClassDefinedInsideTestCase tested = mock(NestedPrivateFinalClassDefinedInsideTestCase.class);\n        when(tested.getValue()).thenReturn(\"something\");\n\n        assertEquals(\"something\", tested.getValue());\n    }\n\n    private class NestedPrivateClassDefinedInsideTestCase {\n        public String getValue() {\n            return \"value\";\n        }\n    }\n\n    private final class NestedPrivateFinalClassDefinedInsideTestCase {\n        public String getValue() {\n            return \"value\";\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingExampleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.partialmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.partialmocking.PartialMockingExample;\n\nimport java.util.List;\nimport java.util.concurrent.CopyOnWriteArrayList;\nimport java.util.concurrent.CountDownLatch;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.doReturn;\nimport static org.powermock.api.mockito.PowerMockito.spy;\n\n/**\n * Asserts that partial mocking (spying) with PowerMockito works for non-final\n * methods.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PartialMockingExample.class)\npublic class PartialMockingExampleTest {\n    \n    @Test\n    public void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocations() throws Exception {\n        final String expected = \"TEST VALUE\";\n        PartialMockingExample underTest = spy(new PartialMockingExample());\n        doReturn(expected).when(underTest).methodToMock();\n        \n        assertEquals(expected, underTest.methodToTest());\n        \n        verify(underTest).methodToTest();\n        verify(underTest).methodToMock();\n    }\n    \n    @Test\n    public void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocationsForMockito() throws Exception {\n        final String expected = \"TEST VALUE\";\n        PartialMockingExample underTest = Mockito.spy(new PartialMockingExample());\n        doReturn(expected).when(underTest).methodToMock();\n        \n        assertEquals(expected, underTest.methodToTest());\n        \n        verify(underTest).methodToTest();\n        verify(underTest).methodToMock();\n    }\n    \n    @Test\n    public void should_verify_spied_object_used_in_other_threads() {\n        \n        final String expected = \"TEST VALUE\";\n        final PartialMockingExample underTest = spy(new PartialMockingExample());\n        doReturn(expected).when(underTest).methodToMock();\n        \n        final int threadCounts = 10;\n        \n        final CountDownLatch startLatch = new CountDownLatch(1);\n        final CountDownLatch endLatch = new CountDownLatch(threadCounts);\n        final List<String> values = new CopyOnWriteArrayList<String>();\n        \n        for (int i = 0; i < threadCounts; i++) {\n            createAndStartThread(i, underTest, startLatch, endLatch, values);\n        }\n        \n        startLatch.countDown();\n        \n        awaitThreads(endLatch);\n        \n        assertThat(values)\n            .as(\"All threads have called method and get expected result\")\n            .hasSize(threadCounts)\n            .containsOnly(expected);\n        \n        verify(underTest, times(threadCounts)).methodToTest();\n        verify(underTest, times(threadCounts)).methodToMock();\n    }\n    \n    private void awaitThreads(final CountDownLatch endLatch) {\n        try {\n            endLatch.await();\n        } catch (InterruptedException e) {\n            e.printStackTrace();\n        }\n    }\n    \n    private void createAndStartThread(final int index, final PartialMockingExample underTest,\n                                      final CountDownLatch startLatch,\n                                      final CountDownLatch endLatch,\n                                      final List<String> values) {\n        Runnable runnable = new Runnable() {\n            @Override\n            public void run() {\n                try {\n                    startLatch.await();\n                } catch (InterruptedException e) {\n                    e.printStackTrace();\n                }\n                values.add(underTest.methodToTest());\n                endLatch.countDown();\n            }\n        };\n        \n        Thread thread = new Thread(runnable, \"mock-use-\" + index);\n        \n        thread.start();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingRetainsStateTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.partialmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.partialmocking.MockSelfDemo;\nimport samples.partialmocking.MockWithStaticStateDemo;\n\nimport static junit.framework.Assert.assertEquals;\n\n/**\n * Demonstrates that PowerMockito retains state when spying. This was previously\n * a bug (issue <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=263\">263</a>).\n */\n@RunWith(PowerMockRunner.class)\npublic class PartialMockingRetainsStateTest {\n\n\t@Test\n    public void spyingOnAnObjectRetainsState() {\n\t\tMockSelfDemo demo = new MockSelfDemo(4);\n\t\tMockSelfDemo spy = PowerMockito.spy(demo);\n\t\tassertEquals(4, spy.getConstructorValue());\n\t}\n\n\t@Test\n    public void spyingOnAClassRetainsState() {\n\t\tPowerMockito.spy(MockWithStaticStateDemo.class);\n\t\tassertEquals(5, MockWithStaticStateDemo.getState());\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PrivatePartialMockingExampleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.partialmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.partialmocking.PrivatePartialMockingExample;\n\nimport java.lang.reflect.Method;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\n\n/**\n * Asserts that partial mocking (spying) with PowerMockito works for non-final\n * private methods.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(PrivatePartialMockingExample.class)\npublic class PrivatePartialMockingExampleTest {\n\n\t@Test\n\tpublic void spyingOnPrivateMethodsWorks() throws Exception {\n\t\tfinal String expected = \"TEST VALUE\";\n\t\tPrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample());\n\t\tfinal String nameOfMethodToMock = \"methodToMock\";\n\t\tfinal String input = \"input\";\n\t\twhen(underTest, nameOfMethodToMock, input).thenReturn(expected);\n\n\t\tassertEquals(expected, underTest.methodToTest());\n\n\t\tverifyPrivate(underTest).invoke(nameOfMethodToMock, input);\n\t}\n\n\t@Test\n\tpublic void partialMockingOfPrivateMethodsWorks() throws Exception {\n\t\tfinal String expected = \"TEST VALUE\";\n\t\tPrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample());\n\t\tfinal String nameOfMethodToMock = \"methodToMock\";\n\t\tfinal String input = \"input\";\n\t\tdoReturn(expected).when(underTest, nameOfMethodToMock, input);\n\n\t\tassertEquals(expected, underTest.methodToTest());\n\n\t\tverifyPrivate(underTest).invoke(nameOfMethodToMock, input);\n\t}\n\n\t@Test\n\tpublic void spyingOnPrivateMethodsWorksWithoutSpecifyingMethodName() throws Exception {\n\t\tfinal String expected = \"TEST VALUE\";\n\t\tPrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample());\n\t\tfinal String input = \"input\";\n\t\tfinal Method methodToMock = method(PrivatePartialMockingExample.class, String.class);\n\t\twhen(underTest, methodToMock).withArguments(input).thenReturn(expected);\n\n\t\tassertEquals(expected, underTest.methodToTest());\n\n\t\tverifyPrivate(underTest).invoke(methodToMock).withArguments(input);\n\t}\n\n\t@Test\n\tpublic void partialMockingOfPrivateMethodsWorksWithoutSpecifyingMethodName() throws Exception {\n\t\tfinal String expected = \"TEST VALUE\";\n\t\tPrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample());\n\t\tfinal String input = \"input\";\n\t\tfinal Method methodToMock = method(PrivatePartialMockingExample.class, String.class);\n\t\tdoReturn(expected).when(underTest, methodToMock).withArguments(input);\n\n\t\tassertEquals(expected, underTest.methodToTest());\n\n\t\tverifyPrivate(underTest).invoke(methodToMock).withArguments(input);\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/StaticPartialMockingTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.partialmocking;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.invocation.InvocationOnMock;\nimport org.mockito.stubbing.Answer;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.partialmocking.MockSelfDemo;\nimport samples.singleton.StaticExample;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport static org.mockito.Mockito.times;\nimport static org.powermock.api.mockito.PowerMockito.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({StaticExample.class, MockSelfDemo.class})\npublic class StaticPartialMockingTest {\n    \n    @Test\n    public void spyingOnStaticMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        assertTrue(Object.class.equals(StaticExample.objectMethod().getClass()));\n        when(StaticExample.class, \"privateObjectMethod\").thenReturn(\"Hello static\");\n        \n        assertEquals(\"Hello static\", StaticExample.objectMethod());\n        /*\n         * privateObjectMethod should be invoked twice, once at \"assertTrue\" and\n\t\t * once above.\n\t\t */\n        verifyPrivate(StaticExample.class, times(2)).invoke(\"privateObjectMethod\");\n    }\n    \n    @Test\n    public void partialMockingOfStaticMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        assertTrue(Object.class.equals(StaticExample.objectMethod().getClass()));\n        doReturn(\"Hello static\").when(StaticExample.class, \"privateObjectMethod\");\n        \n        assertEquals(\"Hello static\", StaticExample.objectMethod());\n\t\t/*\n\t\t * privateObjectMethod should be invoked twice, once at \"assertTrue\" and\n\t\t * once above.\n\t\t */\n        verifyPrivate(StaticExample.class, times(2)).invoke(\"privateObjectMethod\");\n    }\n    \n    @Test\n    public void partialPrivateMockingWithAnswerOfStaticMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        assertTrue(Object.class.equals(StaticExample.objectMethod().getClass()));\n        doAnswer(new Answer<String>() {\n            @Override\n            public String answer(InvocationOnMock invocation) throws Throwable {\n                return \"Hello static\";\n            }\n        }).when(StaticExample.class, \"privateObjectMethod\");\n        \n        assertEquals(\"Hello static\", StaticExample.objectMethod());\n\t\t/*\n\t\t * privateObjectMethod should be invoked twice, once at \"assertTrue\" and\n\t\t * once above.\n\t\t */\n        verifyPrivate(StaticExample.class, times(2)).invoke(\"privateObjectMethod\");\n    }\n    \n    @Test\n    public void spyingOnStaticFinalMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        assertTrue(Object.class.equals(StaticExample.objectFinalMethod().getClass()));\n        \n        when(StaticExample.class, \"privateObjectFinalMethod\").thenReturn(\"Hello static\");\n        \n        assertEquals(\"Hello static\", StaticExample.objectFinalMethod());\n        \n        verifyPrivate(StaticExample.class, times(2)).invoke(\"privateObjectFinalMethod\");\n    }\n    \n    @Test\n    public void partialMockingOfStaticFinalMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        assertTrue(Object.class.equals(StaticExample.objectFinalMethod().getClass()));\n        \n        doReturn(\"Hello static\").when(StaticExample.class, \"privateObjectFinalMethod\");\n        \n        assertEquals(\"Hello static\", StaticExample.objectFinalMethod());\n        \n        verifyPrivate(StaticExample.class, times(2)).invoke(\"privateObjectFinalMethod\");\n    }\n    \n    @Test(expected = ArrayStoreException.class)\n    public void spyingOnStaticVoidMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        StaticExample.voidMethod();\n        \n        when(StaticExample.class, \"privateVoidMethod\").thenThrow(new ArrayStoreException());\n        StaticExample.voidMethod();\n    }\n    \n    @Test(expected = ArrayStoreException.class)\n    public void partialMockingOfStaticVoidMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        StaticExample.voidMethod();\n        \n        doThrow(new ArrayStoreException()).when(StaticExample.class, \"privateVoidMethod\");\n        StaticExample.voidMethod();\n    }\n    \n    @Test(expected = ArrayStoreException.class)\n    public void spyingOnStaticFinalVoidMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        StaticExample.voidFinalMethod();\n        \n        when(StaticExample.class, \"privateVoidFinalMethod\").thenThrow(new ArrayStoreException());\n        StaticExample.voidFinalMethod();\n    }\n    \n    @Test(expected = ArrayStoreException.class)\n    public void partialMockingOfStaticFinalVoidMethodReturningObjectWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        StaticExample.voidFinalMethod();\n        \n        doThrow(new ArrayStoreException()).when(StaticExample.class, \"privateVoidFinalMethod\");\n        StaticExample.voidFinalMethod();\n    }\n    \n    @Test\n    public void partialMockingOfPublicStaticVoidWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        // Given\n        doNothing().when(StaticExample.class);\n        StaticExample.staticVoidMethod();\n        \n        // When\n        StaticExample.staticVoidMethod();\n        \n        // Then\n        verifyStatic(StaticExample.class, times(1));\n        StaticExample.staticVoidMethod();\n    }\n    \n    @Test\n    public void partialMockingOfPublicStaticFinalVoidWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        doNothing().when(StaticExample.class);\n        StaticExample.staticFinalVoidMethod();\n        \n        StaticExample.staticFinalVoidMethod();\n    }\n    \n    @Test\n    public void partialMockingOfNonVoidPublicStaticMethodsWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        doReturn(\"something\").when(StaticExample.class);\n        StaticExample.staticMethodReturningString();\n        \n        assertEquals(\"something\", StaticExample.staticMethodReturningString());\n    }\n    \n    @Test\n    public void partialMockingWithAnswerOfNonVoidPublicStaticMethodsWorks() throws Exception {\n        spy(StaticExample.class);\n        \n        doAnswer(new Answer<String>() {\n            @Override\n            public String answer(InvocationOnMock invocation) throws Throwable {\n                return \"something\";\n            }\n        }).when(StaticExample.class);\n        StaticExample.staticMethodReturningString();\n        \n        assertEquals(\"something\", StaticExample.staticMethodReturningString());\n    }\n    \n    @Test\n    public void partialMockingOfPublicStaticMethodsWorks() throws Exception {\n        spy(MockSelfDemo.class);\n        when(MockSelfDemo.class, method(MockSelfDemo.class, \"methodToBeStubbed\")).withNoArguments().thenReturn(2);\n        \n        int result = MockSelfDemo.getSomething();\n        assertEquals(4, result);\n    }\n    \n    @Test\n    public void partialMockingOfPublicStaticMethodsWorksWhenUsingDoReturn() throws Exception {\n        spy(MockSelfDemo.class);\n        \n        doReturn(2).when(MockSelfDemo.class);\n        MockSelfDemo.methodToBeStubbed();\n        \n        int result = MockSelfDemo.getSomething();\n        assertEquals(4, result);\n    }\n    \n    @Test\n    public void partialMockingOfPublicStaticMethodsWorksWhenUsingDoReturnAndMethodNameAsString() throws Exception {\n        spy(MockSelfDemo.class);\n        \n        doReturn(3).when(MockSelfDemo.class, \"methodToBeStubbed\");\n        \n        int result = MockSelfDemo.getSomething();\n        assertEquals(6, result);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingCases.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.privatemocking;\n\nimport org.junit.Test;\nimport org.mockito.Mockito;\nimport org.mockito.exceptions.base.MockitoAssertionError;\nimport org.mockito.invocation.InvocationOnMock;\nimport org.mockito.stubbing.Answer;\nimport org.powermock.reflect.Whitebox;\nimport samples.privateandfinal.PrivateFinal;\nimport samples.privatemocking.PrivateMethodDemo;\n\nimport java.io.File;\nimport java.io.StringReader;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.anyString;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.never;\nimport static org.powermock.api.mockito.PowerMockito.doReturn;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.spy;\nimport static org.powermock.api.mockito.PowerMockito.verifyPrivate;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\n\npublic class PrivateInstanceMockingCases {\n    \n    @Test\n    public void should_call_method_that_best_match_the_given_parameters_during_verification() throws Exception {\n        final String stubbedValue = \"another\";\n        final PrivateMethodDemo tested = mock(PrivateMethodDemo.class);\n    \n        when(tested.sayYear(anyString(), anyInt())).thenCallRealMethod();\n        when(tested, \"doSayYear\", 12, \"test\").thenReturn(stubbedValue);\n        \n        assertThat(tested.sayYear(\"test\", 12))\n            .as(\"Private method is called\")\n            .isEqualTo(stubbedValue);\n    \n        verifyPrivate(tested).invoke(12, \"test\");\n    }\n    \n    @Test\n    public void expectationsWorkWhenSpyingOnPrivateMethods() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n        assertEquals(\"Hello Temp, you are 50 old.\", tested.sayYear(\"Temp\", 50));\n\n        when(tested, \"doSayYear\", 12, \"test\").thenReturn(\"another\");\n\n        assertEquals(\"Hello Johan, you are 29 old.\", tested.sayYear(\"Johan\", 29));\n        assertEquals(\"another\", tested.sayYear(\"test\", 12));\n\n        verifyPrivate(tested).invoke(\"doSayYear\", 12, \"test\");\n    }\n    \n    @Test\n    public void expectationsWorkWithArgumentMatchersWhenSpyingOnPrivateMethods() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n        assertEquals(\"Hello Temp, you are 50 old.\", tested.sayYear(\"Temp\", 50));\n\n        when(tested, \"doSayYear\", Mockito.anyInt(), Mockito.anyString()).thenReturn(\"another\");\n\n        assertEquals(\"another\", tested.sayYear(\"Johan\", 29));\n        assertEquals(\"another\", tested.sayYear(\"test\", 12));\n\n        verifyPrivate(tested).invoke(\"doSayYear\", 29, \"Johan\");\n        verifyPrivate(tested).invoke(\"doSayYear\", 12, \"test\");\n        verifyPrivate(tested).invoke(\"doSayYear\", 50, \"Temp\");\n    }\n    \n    @Test\n    public void answersWorkWhenSpyingOnPrivateVoidMethods() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n\n        tested.doObjectStuff(new Object());\n\n        when(tested, \"doObjectInternal\", isA(String.class)).thenAnswer(new Answer<Void>() {\n            private static final long serialVersionUID = 20645008237481667L;\n\n            @Override\n            public Void answer(InvocationOnMock invocation) throws Throwable {\n                assertEquals(\"Testing\", invocation.getArguments()[0]);\n                return null;\n            }\n        });\n        tested.doObjectStuff(new Object());\n        tested.doObjectStuff(\"Testing\");\n    }\n    \n    @Test\n    public void spyingOnPrivateFinalMethodsWorksWhenClassIsNotFinal() throws Exception {\n        PrivateFinal tested = spy(new PrivateFinal());\n\n        final String name = \"test\";\n        tested.say(name);\n        assertEquals(\"Hello \" + name, tested.say(name));\n\n        when(tested, \"sayIt\", name).thenReturn(\"First\", \"Second\");\n\n        assertEquals(\"First\", tested.say(name));\n        assertEquals(\"Second\", tested.say(name));\n    }\n    \n    @Test\n    public void errorousVerificationOnPrivateMethodGivesFilteredErrorMessage() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n        assertEquals(\"Hello Temp, you are 50 old.\", tested.sayYear(\"Temp\", 50));\n\n        when(tested, \"doSayYear\", Mockito.anyInt(), Mockito.anyString()).thenReturn(\"another\");\n\n        assertEquals(\"another\", tested.sayYear(\"Johan\", 29));\n        assertEquals(\"another\", tested.sayYear(\"test\", 12));\n\n        try {\n            verifyPrivate(tested, never()).invoke(\"doSayYear\", 50, \"Temp\");\n            fail(\"Should throw assertion error\");\n        } catch (MockitoAssertionError e) {\n            assertThat(e.getMessage())\n                      .as(\"Never wanted  but invoked\")\n                      .contains(\"Never wanted  but invoked\");\n        }\n    }\n    \n    @Test\n    public void expectationsWorkWhenSpyingOnPrivateMethodsUsingDoReturn() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n        assertEquals(\"Hello Temp, you are 50 old.\", tested.sayYear(\"Temp\", 50));\n        \n        doReturn(\"another\").when(tested, \"doSayYear\", 12, \"test\");\n        \n        assertEquals(\"Hello Johan, you are 29 old.\", tested.sayYear(\"Johan\", 29));\n        assertEquals(\"another\", tested.sayYear(\"test\", 12));\n        \n        verifyPrivate(tested).invoke(\"doSayYear\", 12, \"test\");\n    }\n    \n    @Test\n    public void expectationsWorkWhenSpyingOnPrivateMethodsUsingDoReturnWhenMethodDoesntHaveAnyArguments() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n        \n        doReturn(\"another\").when(tested, \"sayIt\");\n        \n        assertEquals(\"another\", Whitebox.invokeMethod(tested, \"sayIt\"));\n        \n        verifyPrivate(tested).invoke(\"sayIt\");\n    }\n    \n    @Test\n    public void verifyPrivateMethodWhenNoExpectationForTheMethodHasBeenMade() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n        \n        assertEquals(\"Hello Johan, you are 29 old.\", tested.sayYear(\"Johan\", 29));\n        \n        verifyPrivate(tested).invoke(\"doSayYear\", 29, \"Johan\");\n    }\n    \n    @Test(expected = ArrayStoreException.class)\n    public void expectationsWorkWhenSpyingOnPrivateVoidMethods() throws Exception {\n        PrivateMethodDemo tested = spy(new PrivateMethodDemo());\n        \n        tested.doObjectStuff(new Object());\n        \n        when(tested, \"doObjectInternal\", isA(Object.class)).thenThrow(new ArrayStoreException());\n        \n        tested.doObjectStuff(new Object());\n    }\n    \n    @Test\n    public void usingMultipleArgumentsOnPrivateMethodWorks() throws Exception {\n        File file = mock(File.class);\n        StringReader expected = new StringReader(\"Some string\");\n        \n        PrivateMethodDemo tested = mock(PrivateMethodDemo.class);\n        doReturn(expected).when(tested, method(PrivateMethodDemo.class, \"createReader\", File.class)).withArguments(file);\n        \n        StringReader actual = Whitebox.invokeMethod(tested, \"createReader\", file);\n        \n        assertSame(expected, actual);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingTest.java",
    "content": "package samples.powermockito.junit4.privatemocking;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.privatemocking.PrivateMethodDemo;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({PrivateMethodDemo.class})\npublic class PrivateInstanceMockingTest extends PrivateInstanceMockingCases {\n    \n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/proxymethod/ProxyMethodTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.proxymethod;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.suppressmethod.SuppressMethod;\nimport samples.suppressmethod.SuppressMethodExample;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.replace;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(SuppressMethod.class)\npublic class ProxyMethodTest {\n\n\t@Test(expected = ArrayStoreException.class)\n\tpublic void expectionThrowingMethodProxyWorksForJavaLangReflectMethods() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObject\")).with(new ThrowingInvocationHandler());\n\n\t\tnew SuppressMethod().getObject();\n\t}\n\n\t@Test(expected = ArrayStoreException.class)\n\tpublic void expectionThrowingMethodProxyWorksForMethodNames() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObject\")).with(new ThrowingInvocationHandler());\n\n\t\tnew SuppressMethod().getObject();\n\t}\n\n\t@Test\n\tpublic void returnValueChangingMethodProxyWorksForMethodNames() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObject\")).with(new ReturnValueChangingInvocationHandler());\n\n\t\tassertEquals(\"hello world\", new SuppressMethod().getObject());\n\t}\n\n\t@Test\n\tpublic void delegatingMethodProxyWorksForMethodNames() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObject\")).with(new DelegatingInvocationHandler());\n\n\t\tassertSame(SuppressMethod.OBJECT, new SuppressMethod().getObject());\n\t}\n\n\t@Test\n\tpublic void mockingAndMethodProxyAtTheSameTimeWorks() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObjectStatic\")).with(new DelegatingInvocationHandler());\n\t\tSuppressMethod tested = mock(SuppressMethod.class);\n\n\t\twhen(tested.getObject()).thenReturn(\"Hello world\");\n\n\t\tassertSame(SuppressMethod.OBJECT, SuppressMethod.getObjectStatic());\n\n\t\tassertEquals(\"Hello world\", tested.getObject());\n\n\t\tverify(tested).getObject();\n\t}\n\n\t@Test\n\t@Ignore(\"Doesn't work atm\")\n\tpublic void replaceInstanceMethodsWork() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObject\")).with(method(SuppressMethodExample.class, \"getStringObject\"));\n\t\tSuppressMethod tested = new SuppressMethod();\n\t\tassertEquals(\"test\", tested.getObject());\n\t}\n\n\t@Test(expected = IllegalArgumentException.class)\n\tpublic void replaceInstanceMethodToStaticMethodDoesntWork() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObject\")).with(method(SuppressMethodExample.class, \"getStringObjectStatic\"));\n\t}\n\t\n\t@Test(expected = IllegalArgumentException.class)\n\tpublic void replaceStaticMethodToInstaceMethodDoesntWork() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObjectStatic\")).with(method(SuppressMethodExample.class, \"getStringObject\"));\n\t}\n\n\n\t@Test\n\tpublic void replaceStaticMethodsWork() throws Exception {\n\t\treplace(method(SuppressMethod.class, \"getObjectStatic\")).with(method(SuppressMethodExample.class, \"getStringObjectStatic\"));\n\t\tassertEquals(\"test\", SuppressMethod.getObjectStatic());\n\t}\n\n\tprivate final class ThrowingInvocationHandler implements InvocationHandler {\n\t\t@Override\n\t\tpublic Object invoke(Object object, Method method, Object[] arguments) throws Throwable {\n\t\t\tthrow new ArrayStoreException();\n\t\t}\n\t}\n\n\tprivate final class ReturnValueChangingInvocationHandler implements InvocationHandler {\n\t\t@Override\n\t\tpublic Object invoke(Object object, Method method, Object[] arguments) throws Throwable {\n\t\t\treturn \"hello world\";\n\t\t}\n\t}\n\n\tprivate final class DelegatingInvocationHandler implements InvocationHandler {\n\t\t@Override\n\t\tpublic Object invoke(Object object, Method method, Object[] arguments) throws Throwable {\n\t\t\treturn method.invoke(object, arguments);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/simplemix/SimpleMixTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.simplemix;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PowerMockListener;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.testlisteners.FieldDefaulter;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.reflect.Whitebox;\nimport samples.simplemix.SimpleMix;\nimport samples.simplemix.SimpleMixCollaborator;\nimport samples.simplemix.SimpleMixConstruction;\nimport samples.simplemix.SimpleMixUtilities;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\n\n/**\n * Demonstrates PowerMockito features such as static mocking, final mocking,\n * partial mocking and setting internal state. It also demonstrates\n * test-chunking and final system class mocking.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockListener(FieldDefaulter.class)\npublic class SimpleMixTest {\n\n    @PrepareForTest( { SimpleMixUtilities.class, SimpleMixCollaborator.class, SimpleMix.class })\n    @Test\n    public void staticPartialFinalMocking() throws Exception {\n        SimpleMix tested = spy(new SimpleMix());\n\n        when(tested, \"getValue\").thenReturn(0);\n        SimpleMixCollaborator simpleMixCollaboratorMock = mock(SimpleMixCollaborator.class);\n        mockStatic(SimpleMixUtilities.class);\n        SimpleMixConstruction simpleMixConstructionMock = mock(SimpleMixConstruction.class);\n\n        Whitebox.setInternalState(tested, simpleMixCollaboratorMock);\n\n        when(SimpleMixUtilities.getRandomInteger()).thenReturn(10);\n        when(simpleMixCollaboratorMock.getRandomInteger()).thenReturn(6);\n        whenNew(SimpleMixConstruction.class).withNoArguments().thenReturn(simpleMixConstructionMock);\n        when(simpleMixConstructionMock.getMyValue()).thenReturn(1);\n\n        assertEquals(4, tested.calculate());\n\n        verifyStatic(SimpleMixUtilities.class);\n        SimpleMixUtilities.getRandomInteger();\n        verifyNew(SimpleMixConstruction.class).withNoArguments();\n        \n        verifyPrivate(tested)\n            .invoke(method(SimpleMix.class, \"getValue\"))\n        .withNoArguments();\n    }\n\n    @PrepareForTest( { SimpleMix.class })\n    @Test\n    public void finalSystemClassMocking() throws Exception {\n        SimpleMix tested = new SimpleMix();\n        mockStatic(System.class);\n\n        when(System.currentTimeMillis()).thenReturn(2000L);\n\n        assertEquals(2, Whitebox.invokeMethod(tested, \"getValue\"));\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/spy/SpyTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.spy;\n\nimport org.assertj.core.api.Assertions;\nimport org.assertj.core.api.Java6Assertions;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.spy.SpyObject;\nimport samples.suppressmethod.SuppressMethod;\nimport samples.suppressmethod.SuppressMethodParent;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.doNothing;\nimport static org.powermock.api.mockito.PowerMockito.spy;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({SpyObject.class, SuppressMethod.class, SuppressMethodParent.class})\npublic class SpyTest {\n\n    private SpyObject partialMock = null;\n\n    @Before\n    public void setup() throws Exception {\n        partialMock = spy(new SpyObject());\n    }\n\n    @Test\n    public void should_stub_spying_on_private_method_works() throws Exception {\n        when(partialMock, \"getMyString\").thenReturn(\"ikk2\");\n\n        assertThat(partialMock.getMyString(), equalTo(\"ikk2\"));\n        assertThat(partialMock.getStringTwo(), equalTo(\"two\"));\n    }\n    \n    @Test\n    public void should_call_real_method_when_spy_method_is_not_stubbed() {\n        Java6Assertions.assertThat(partialMock.getMyString())\n                       .as(\"Real method is called\")\n                       .isEqualTo(new SpyObject().getMyString());\n    }\n    \n\n    @Test\n    public void testSuppressMethodWhenObjectIsSpy() throws Exception {\n        suppress(method(SuppressMethod.class, \"myMethod\"));\n\n        SuppressMethod tested = spy(new SuppressMethod());\n        assertEquals(0, tested.myMethod());\n    }\n\n    @Test\n    public void testSuppressMethodInParentOnlyWhenObjectIsSpy() throws Exception {\n        suppress(method(SuppressMethodParent.class, \"myMethod\"));\n\n        SuppressMethod tested = spy(new SuppressMethod());\n        assertEquals(20, tested.myMethod());\n    }\n\n    @Test\n    public void testDoNothingForSpy() {\n        doNothing().when(partialMock).throwException();\n\n        partialMock.throwException();\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/LocationFromStackTraceTest.java",
    "content": "package samples.powermockito.junit4.stacktracecleaner;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.internal.stubbing.InvocationContainerImpl;\nimport org.mockito.internal.util.MockUtil;\nimport org.mockito.invocation.Location;\nimport org.mockito.invocation.MockHandler;\nimport org.mockito.junit.MockitoJUnitRunner;\nimport org.mockito.stubbing.Stubbing;\nimport org.powermock.api.mockito.invocation.MockHandlerAdaptor;\nimport org.powermock.api.mockito.invocation.MockitoMethodInvocationControl;\nimport org.powermock.core.MockRepository;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.junit.Assert.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.doNothing;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n/**\n * Ensures Location.toString returns the location where a mock is declared.  The filtering of the stack trace used\n * to determine the location is performed by the StackTraceCleaner in StackTraceCleanerProvider.\n */\n@RunWith(value = PowerMockRunner.class)\n@PowerMockRunnerDelegate(MockitoJUnitRunner.StrictStubs.class)\n@PrepareForTest({SomethingWithStaticMethod.class})\npublic class LocationFromStackTraceTest {\n    @Test\n    public void should_filter_extra_elements_in_stack_when_mocking_static_method() throws Exception {\n        mockStatic(SomethingWithStaticMethod.class);\n        when(SomethingWithStaticMethod.doStaticOne()).thenReturn(\"Something else 1\");\n        when(SomethingWithStaticMethod.doStaticTwo()).thenReturn(\"Something else 2\");\n        doNothing().when(SomethingWithStaticMethod.class, \"doStaticVoid\");\n\n        MockitoMethodInvocationControl invocationControl =\n                (MockitoMethodInvocationControl)\n                        MockRepository.getStaticMethodInvocationControl(SomethingWithStaticMethod.class);\n        MockHandlerAdaptor mockHandlerAdaptor = invocationControl.getMockHandlerAdaptor();\n        Object mock = mockHandlerAdaptor.getMock();\n        MockHandler<?> mockHandler = MockUtil.getMockHandler(mock);\n        InvocationContainerImpl invocationContainer = (InvocationContainerImpl)mockHandler.getInvocationContainer();\n        List<Stubbing> stubbings = new ArrayList<Stubbing>(invocationContainer.getStubbingsAscending());\n        assertThat(stubbings.size(), is(3));\n        Location static1Location = stubbings.get(0).getInvocation().getLocation();\n        assertThat(static1Location.toString(), is(\"-> at samples.powermockito.junit4.stacktracecleaner.\" +\n                \"LocationFromStackTraceTest.should_filter_extra_elements_in_stack_when_mocking_static_method(\" +\n                \"LocationFromStackTraceTest.java:37)\"));\n        Location static2Location = stubbings.get(1).getInvocation().getLocation();\n        assertThat(static2Location.toString(), is(\"-> at samples.powermockito.junit4.stacktracecleaner.\" +\n                \"LocationFromStackTraceTest.should_filter_extra_elements_in_stack_when_mocking_static_method(\" +\n                \"LocationFromStackTraceTest.java:38)\"));\n        Location staticVoidLocation = stubbings.get(2).getInvocation().getLocation();\n        assertThat(staticVoidLocation.toString(), is(\"-> at samples.powermockito.junit4.stacktracecleaner.\" +\n                \"LocationFromStackTraceTest.should_filter_extra_elements_in_stack_when_mocking_static_method(\" +\n                \"LocationFromStackTraceTest.java:39)\"));\n        \n        // Removing these calls and the three Location assertions above will cause the test to fail due to the\n        // strict stubs.  Without the alterations to StackTraceCleanerProvider, the failure messages will contain\n        // an item in the stack trace inside the powermock libraries.\n        assertThat(SomethingWithStaticMethod.doStaticOne(), is(\"Something else 1\"));\n        assertThat(SomethingWithStaticMethod.doStaticTwo(), is(\"Something else 2\"));\n        SomethingWithStaticMethod.doStaticVoid();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/SomethingWithStaticMethod.java",
    "content": "package samples.powermockito.junit4.stacktracecleaner;\n\npublic class SomethingWithStaticMethod {\n    public static String doStaticOne() {\n        return \"I am static 1\";\n    } \n\n    public static String doStaticTwo() {\n        return \"I am static 2\";\n    }\n    \n    public static void doStaticVoid() {\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticandinstance/StaticAndInstanceDemoTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.staticandinstance;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.staticandinstance.StaticAndInstanceDemo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class StaticAndInstanceDemoTest {\n    \n    @Test\n    public void partialMockingOfStaticAndInstanceMethod() throws Exception {\n        spy(StaticAndInstanceDemo.class);\n        StaticAndInstanceDemo tested = spy(new StaticAndInstanceDemo());\n        \n        final String staticExpected = \"a static message\";\n        when(StaticAndInstanceDemo.getStaticMessage()).thenReturn(staticExpected);\n        final String privateExpected = \"A private message \";\n        when(tested, \"getPrivateMessage\").thenReturn(privateExpected);\n        \n        String actual = tested.getMessage();\n    \n        assertEquals(privateExpected + staticExpected, actual);\n        \n        verifyStatic(StaticAndInstanceDemo.class);\n        StaticAndInstanceDemo.getStaticMessage();\n    \n        verifyPrivate(tested).invoke(\"getPrivateMessage\");\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticCases.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.staticmocking;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.mockito.ArgumentCaptor;\nimport org.mockito.exceptions.base.MockitoAssertionError;\nimport org.mockito.exceptions.verification.TooFewActualInvocations;\nimport org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;\nimport samples.singleton.SimpleStaticService;\nimport samples.singleton.StaticService;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.atLeastOnce;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.when;\nimport static org.powermock.api.mockito.PowerMockito.doCallRealMethod;\nimport static org.powermock.api.mockito.PowerMockito.doNothing;\nimport static org.powermock.api.mockito.PowerMockito.doThrow;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.spy;\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\n\npublic class MockStaticCases {\n    \n    @Test\n    public void should_call_reall_static_void_method() {\n        mockStatic(StaticService.class);\n        \n        StaticService.throwException();\n        \n        doCallRealMethod().when(StaticService.class);\n        StaticService.throwException();\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                StaticService.throwException();\n            }\n        }).as(\"Real method is called\")\n          .isInstanceOf(RuntimeException.class);\n        \n    }\n    \n    @Test\n    public void mockStatic_uses_var_args_to_create_multiple_static_mocks() throws Exception {\n        mockStatic(StaticService.class, SimpleStaticService.class);\n        \n        when(SimpleStaticService.say(\"Something\")).thenReturn(\"other\");\n        \n        StaticService.sayHello();\n        final String said = SimpleStaticService.say(\"Something\");\n        \n        verifyStatic(StaticService.class);\n        StaticService.sayHello();\n        verifyStatic(SimpleStaticService.class);\n        SimpleStaticService.say(\"Something\");\n        \n        assertEquals(said, \"other\");\n    }\n    \n    @Test\n    public void should_verify_behaviour_of_specified_in_verify_static_class() {\n        mockStatic(StaticService.class);\n        \n        StaticService.sayHello();\n        \n        verifyStatic(StaticService.class);\n        StaticService.sayHello();\n    }\n    \n    @Test\n    public void should_not_verify_behaviour_of_another_mock_class_not_specified_in_verify_static_class() {\n        mockStatic(StaticService.class);\n        mockStatic(SimpleStaticService.class);\n        \n        StaticService.sayHello();\n        \n        verifyStatic(StaticService.class);\n        \n        SimpleStaticService.say(\"Something\");\n        StaticService.sayHello();\n    }\n    \n    @Test\n    public void testMockStaticNoExpectations() throws Exception {\n        mockStatic(StaticService.class);\n        assertNull(StaticService.say(\"hello\"));\n        \n        // Verification is done in two steps using static methods.\n        verifyStatic(StaticService.class);\n        StaticService.say(\"hello\");\n    }\n    \n    @Test\n    public void testMockStaticWithExpectations() throws Exception {\n        final String expected = \"Hello world\";\n        final String argument = \"hello\";\n        \n        mockStatic(StaticService.class);\n        \n        when(StaticService.say(argument)).thenReturn(expected);\n        \n        assertEquals(expected, StaticService.say(argument));\n        \n        // Verification is done in two steps using static methods.\n        verifyStatic(StaticService.class);\n        StaticService.say(argument);\n    }\n    \n    @Test\n    public void errorousVerificationOfStaticMethodsGivesANonMockitoStandardMessage() throws Exception {\n        final String expected = \"Hello world\";\n        final String argument = \"hello\";\n        \n        mockStatic(StaticService.class);\n        \n        when(StaticService.say(argument)).thenReturn(expected);\n        \n        assertEquals(expected, StaticService.say(argument));\n        \n        // Verification is done in two steps using static methods.\n        verifyStatic(StaticService.class, times(2));\n        try {\n            StaticService.say(argument);\n            fail(\"Should throw assertion error\");\n        } catch (MockitoAssertionError e) {\n            assertEquals(\"\\nsamples.singleton.StaticService.say(\\\"hello\\\");\\nWanted 2 times but was 1 time.\", e.getMessage());\n        }\n    }\n    \n    @Test(expected = IllegalStateException.class)\n    public void testMockStaticThatThrowsException() throws Exception {\n        final String argument = \"hello\";\n        \n        mockStatic(StaticService.class);\n        \n        when(StaticService.say(argument)).thenThrow(new IllegalStateException());\n        \n        StaticService.say(argument);\n    }\n    \n    @Test(expected = ArgumentsAreDifferent.class)\n    public void testMockStaticVerificationFails() throws Exception {\n        mockStatic(StaticService.class);\n        assertNull(StaticService.say(\"hello\"));\n        \n        // Verification is done in two steps using static methods.\n        verifyStatic(StaticService.class);\n        StaticService.say(\"Hello\");\n    }\n    \n    @Test\n    public void testMockStaticAtLeastOnce() throws Exception {\n        mockStatic(StaticService.class);\n        assertNull(StaticService.say(\"hello\"));\n        assertNull(StaticService.say(\"hello\"));\n        \n        // Verification is done in two steps using static methods.\n        verifyStatic(StaticService.class, atLeastOnce());\n        StaticService.say(\"hello\");\n    }\n    \n    @Test\n    public void testMockStaticCorrectTimes() throws Exception {\n        mockStatic(StaticService.class);\n        assertNull(StaticService.say(\"hello\"));\n        assertNull(StaticService.say(\"hello\"));\n        \n        // Verification is done in two steps using static methods.\n        verifyStatic(StaticService.class, times(2));\n        StaticService.say(\"hello\");\n    }\n    \n    @Test(expected = TooFewActualInvocations.class)\n    public void testMockStaticIncorrectTimes() throws Exception {\n        mockStatic(StaticService.class);\n        assertNull(StaticService.say(\"hello\"));\n        assertNull(StaticService.say(\"hello\"));\n        \n        // Verification is done in two steps using static methods.\n        verifyStatic(StaticService.class, times(3));\n        StaticService.say(\"hello\");\n    }\n    \n    @Test\n    public void testMockStaticVoidWithNoExpectations() throws Exception {\n        mockStatic(StaticService.class);\n        \n        StaticService.sayHello();\n        \n        verifyStatic(StaticService.class);\n        StaticService.sayHello();\n    }\n    \n    @Test(expected = ArrayStoreException.class)\n    public void testMockStaticVoidWhenThrowingException() throws Exception {\n        mockStatic(StaticService.class);\n        \n        // Expectations\n        doThrow(new ArrayStoreException(\"Mock error\")).when(StaticService.class);\n        StaticService.sayHello();\n        \n        // Test\n        StaticService.sayHello();\n    }\n    \n    @Test\n    public void testSpyOnStaticMethods() throws Exception {\n        spy(StaticService.class);\n        \n        String expectedMockValue = \"expected\";\n        when(StaticService.say(\"world\")).thenReturn(expectedMockValue);\n        \n        assertEquals(expectedMockValue, StaticService.say(\"world\"));\n        assertEquals(\"Hello world2\", StaticService.say(\"world2\"));\n    }\n    \n    @Test\n    public void spyingUsingArgumentCaptor() throws Exception {\n// Given\n        mockStatic(StaticService.class);\n        final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);\n        \n        StaticService.say(\"something\");\n        \n        verifyStatic(StaticService.class);\n        StaticService.say(captor.capture());\n        \n        assertEquals(\"something\", captor.getValue());\n    }\n    \n    @Test\n    public void testMockStaticWithExpectations_withDo() throws Exception {\n        final String argument = \"hello\";\n        \n        mockStatic(StaticService.class);\n        \n        doNothing().when(StaticService.class, \"sayHello\", any(String.class));\n        \n        StaticService.sayHello(argument);\n        \n        assertThat(StaticService.messageStorage).isNull();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.staticmocking;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.singleton.SimpleStaticService;\nimport samples.singleton.StaticService;\n\n/**\n * Test class to demonstrate static mocking with PowerMockito.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({StaticService.class, SimpleStaticService.class})\npublic class MockStaticTest extends MockStaticCases {\n    \n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stress/PowerMockStressTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.stress;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.stress.ClassWithStatic;\nimport samples.stress.StressSample;\n\nimport static org.mockito.Mockito.when;\n\n/**\n * Test that asserts that <a href=\"http://code.google.com/p/powermock/issues/detail?id=308\">issue 308</a> is resolved.\n * The problem was that finalize methods could be called before an expected method because the GC kicked in too soon\n * since now object held a reference to the mock.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({ClassWithStatic.class})\npublic class PowerMockStressTest {\n\t\n\tprivate StressSample underTest = new StressSample();\n\n\t@Before\n\tpublic void setUp(){\n\t\tPowerMockito.mockStatic(ClassWithStatic.class);\n\t\tfor (int i = 0; i < 1000; i++) { // 100*8executions\n\t\t\tcreateWhen();\n\t\t}\n\t}\n\tpublic void createWhen(){\n\t\twhen(ClassWithStatic.a()).thenReturn(\"A\");\n\t\twhen(ClassWithStatic.b()).thenReturn(\"B\");\n\t\twhen(ClassWithStatic.c()).thenReturn(\"C\");\n\t\twhen(ClassWithStatic.d()).thenReturn(\"D\");\n\t\twhen(ClassWithStatic.e()).thenReturn(\"E\");\n\t\twhen(ClassWithStatic.f()).thenReturn(\"F\");\n\t\twhen(ClassWithStatic.g()).thenReturn(\"G\");\n\t\twhen(ClassWithStatic.h()).thenReturn(\"H\");\n\t}\n\t\n\t@Test\n\tpublic void test1(){\n\t\tunderTest.a1();\n\t}\n\t@Test\n\tpublic void test2(){\n\t\tunderTest.b1();\n\t}\n\t@Test\n\tpublic void test3(){\n\t\tunderTest.c1();\n\t}\n\t@Test\n\tpublic void test4(){\n\t\tunderTest.d1();\n\t}\n\t@Test\n\tpublic void test5(){\n\t\tunderTest.e1();\n\t}\n\t@Test\n\tpublic void test6(){\n\t\tunderTest.f1();\n\t}\n\t@Test\n\tpublic void test7(){\n\t\tunderTest.g1();\n\t}\n\t@Test\n\tpublic void test8(){\n\t\tunderTest.h1();\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/ServiceLoaderTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.system;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.util.ServiceLoader;\n\nimport static org.powermock.api.mockito.PowerMockito.doThrow;\nimport static org.powermock.api.mockito.PowerMockito.mock;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ServiceLoader.class)\npublic class ServiceLoaderTest {\n\n    @Test(expected = IllegalArgumentException.class)\n    public void supportsMockingServiceLoader() throws Exception {\n        final ServiceLoader mock = mock(ServiceLoader.class);\n\n        doThrow(new IllegalArgumentException(\"something\"))\n            .when(mock)\n            .reload();\n\n        mock.reload();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.system;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.invocation.InvocationOnMock;\nimport org.mockito.stubbing.Answer;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.system.SystemClassUser;\n\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.UUID;\n\nimport static org.junit.Assert.*;\nimport static org.mockito.BDDMockito.given;\nimport static org.mockito.ArgumentMatchers.anyLong;\nimport static org.mockito.Mockito.times;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n/**\n * Demonstrates PowerMockito's ability to mock non-final and final system\n * classes. To mock a system class you need to prepare the calling class for\n * testing. I.e. let's say you're testing class A which interacts with\n * URLEncoder then you would do:\n * <p>\n * <pre>\n *\n * &#064;PrepareForTest({A.class})\n *\n * </pre>\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({SystemClassUser.class})\npublic class SystemClassUserTest {\n    \n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n        \n        when(URLEncoder.encode(\"string\", \"enc\")).thenReturn(\"something\");\n        \n        assertEquals(\"something\", new SystemClassUser().performEncode());\n        \n    }\n    \n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n        \n        Runtime runtimeMock = mock(Runtime.class);\n        Process processMock = mock(Process.class);\n        \n        when(Runtime.getRuntime()).thenReturn(runtimeMock);\n        when(runtimeMock.exec(\"command\")).thenReturn(processMock);\n        \n        assertSame(processMock, new SystemClassUser().executeCommand());\n    }\n    \n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n        \n        when(System.getProperty(\"property\")).thenReturn(\"my property\");\n        \n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n    }\n    \n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        spy(System.class);\n\n        doReturn(2L).when(System.class);\n        System.nanoTime();\n        \n        new SystemClassUser().doMoreComplicatedStuff();\n        \n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n    }\n    \n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n        \n        Collections.shuffle(list);\n        \n        new SystemClassUser().shuffleCollection(list);\n        \n        verifyStatic(Collections.class, times(2));\n        Collections.shuffle(list);\n    }\n    \n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        spy(System.class);\n\n        doReturn(\"my property\").when(System.class);\n        System.getProperty(\"property\");\n        \n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n\n        assertEquals(\"my property\", System.getProperty(\"to\"));\n    }\n    \n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n        \n        when(String.format(string, args)).thenReturn(returnValue);\n        \n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n    }\n    \n    @Test\n    public void mockingStaticVoidMethodWorks() throws Exception {\n        mockStatic(Thread.class);\n        doNothing().when(Thread.class);\n        Thread.sleep(anyLong());\n        \n        long startTime = System.currentTimeMillis();\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.threadSleep();\n        long endTime = System.currentTimeMillis();\n        assertTrue(endTime - startTime < 5000);\n    }\n    \n    @Test\n    public void mockingURLWorks() throws Exception {\n        URL url = mock(URL.class);\n        URLConnection urlConnectionMock = mock(URLConnection.class);\n        \n        when(url.openConnection()).thenReturn(urlConnectionMock);\n        \n        URLConnection openConnection = url.openConnection();\n        \n        assertSame(openConnection, urlConnectionMock);\n    }\n    \n    @Test\n    public void mockingUUIDWorks() throws Exception {\n        // given\n        final UUID mock = mock(UUID.class);\n        mockStatic(UUID.class);\n        given(UUID.randomUUID()).willReturn(mock);\n        given(mock.toString()).willCallRealMethod();\n        \n        // when\n        String actual = new SystemClassUser().generatePerishableToken();\n        \n        // then\n        assertEquals(\"00000000000000000000000000000000\", actual);\n    }\n    \n    @Test\n    public void mockingNewURLWorks() throws Exception {\n        // Given\n        final URL url = mock(URL.class);\n        whenNew(URL.class).withArguments(\"some_url\").thenReturn(url);\n        \n        // When\n        final URL actual = new SystemClassUser().newURL(\"some_url\");\n        \n        // Then\n        assertSame(url, actual);\n    }\n    \n    @Test\n    public void mockingStringBuilder() throws Exception {\n        // Given\n        final StringBuilder mock = mock(StringBuilder.class);\n        whenNew(StringBuilder.class).withNoArguments().thenReturn(mock);\n        when(mock.toString()).thenReturn(\"My toString\");\n        \n        // When\n        final StringBuilder actualStringBuilder = new SystemClassUser().newStringBuilder();\n        final String actualToString = actualStringBuilder.toString();\n        \n        \n        // Then\n        assertSame(mock, actualStringBuilder);\n        assertEquals(\"My toString\", actualToString);\n    }\n    \n    @Test(expected = IllegalStateException.class)\n    public void triggerMockedCallFromInterfaceTypeInsteadOfConcreteType() throws Exception {\n        StringBuilder builder = mock(StringBuilder.class);\n        when(builder.length()).then(new Answer<StringBuilder>() {\n            public StringBuilder answer(InvocationOnMock invocation) throws Throwable {\n                throw new IllegalStateException(\"Can't really happen\");\n            }\n        });\n        new SystemClassUser().lengthOf(builder);\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/tostring/ToStringTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.tostring;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport javax.crypto.Cipher;\n\nimport static org.junit.Assert.assertNotNull;\n\n/**\n * Test that demonstrates that <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=239\">issue 239</a>\n * is resolved.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(ToStringTest.class)\npublic class ToStringTest {\n    private Cipher cipher;\n\n    @Test\n    public void toStringInvocationWorksInMockito() throws Exception {\n        cipher = PowerMockito.mock(Cipher.class);\n\n        assertNotNull(cipher.toString());\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyNoMoreInteractionsTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.verify;\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mockito;\nimport org.mockito.exceptions.base.MockitoAssertionError;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.Mockito.times;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.verifyNew;\nimport static org.powermock.api.mockito.PowerMockito.verifyNoMoreInteractions;\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\nimport static org.powermock.api.mockito.PowerMockito.whenNew;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\n\n/**\n * Test class to demonstrate static mocking with PowerMockito.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticService.class, StaticHelper.class, ExpectNewDemo.class })\npublic class VerifyNoMoreInteractionsTest {\n\n\t@Test\n\tpublic void verifyNoMoreInteractionsForStaticMethodsReturnsSilentlyWhenNoMoreInteractionsTookPlace() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tassertNull(StaticService.say(\"hello\"));\n\n\t\tverifyStatic(StaticService.class);\n\t\tStaticService.say(\"hello\");\n\t\tverifyNoMoreInteractions(StaticService.class);\n\t}\n\n\t@Test\n\tpublic void verifyNoMoreInteractionsOnMethodThrowsAssertionErrorWhenMoreInteractionsTookPlace() throws Exception {\n\t\tmockStatic(StaticService.class);\n\t\tassertNull(StaticService.say(\"hello\"));\n\n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                verifyNoMoreInteractions(StaticService.class);\n            }\n        }).hasMessageStartingWith(\n            \"\\nNo interactions wanted here:\\n-> at samples.powermockito.junit4.verify.VerifyNoMoreInteractionsTest$1.call\");\n\t}\n\n\t@Test\n\tpublic void verifyNoMoreInteractionsOnNewInstancesThrowsAssertionErrorWhenMoreInteractionsTookPlace() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\n\t\tMyClass myClassMock = mock(MyClass.class);\n\n\t\twhenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n\t\ttested.simpleMultipleNew();\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                verifyNoMoreInteractions(MyClass.class);\n            }\n        }).hasMessageStartingWith(\n            \"\\nNo interactions wanted here:\\n-> at samples.powermockito.junit4.verify.VerifyNoMoreInteractionsTest$2.call\");\n\t}\n\n\t@Test\n\tpublic void verifyNoMoreInteractionsOnNewInstancesWorks() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\n\t\tMyClass myClassMock = mock(MyClass.class);\n\n\t\twhenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n\t\ttested.simpleMultipleNew();\n\n\t\tverifyNew(MyClass.class, times(3)).withNoArguments();\n\t\tverifyNoMoreInteractions(MyClass.class);\n\t}\n\n\t@Test\n\tpublic void verifyNoMoreInteractionsOnNewInstancesWorksWhenUsingConstructorToExpect() throws Exception {\n\t\tExpectNewDemo tested = new ExpectNewDemo();\n\n\t\tMyClass myClassMock = mock(MyClass.class);\n\n\t\twhenNew(constructor(MyClass.class)).withNoArguments().thenReturn(myClassMock);\n\n\t\ttested.simpleMultipleNew();\n\n\t\tverifyNew(MyClass.class, times(3)).withNoArguments();\n\t\tverifyNoMoreInteractions(MyClass.class);\n\t}\n\n\t@Test\n\tpublic void verifyNoMoreInteractionsDelegatesToPlainMockitoWhenMockIsNotAPowerMockitoMock() throws Exception {\n\t\tfinal MyClass myClassMock = Mockito.mock(MyClass.class);\n        myClassMock.getMessage();\n        \n        final String expectedTextThatProvesDelegation = \"But found this interaction\";\n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                verifyNoMoreInteractions(myClassMock);\n            }\n        }).hasMessageContaining(expectedTextThatProvesDelegation);\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyZeroInteractionsTest.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.powermockito.junit4.verify;\n\n\nimport org.assertj.core.api.ThrowableAssert.ThrowingCallable;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.exceptions.verification.NoInteractionsWanted;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.Service;\nimport samples.singleton.StaticExample;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.assertj.core.api.Java6Assertions.assertThatThrownBy;\nimport static org.assertj.core.api.Assertions.catchThrowable;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.verifyZeroInteractions;\n\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(StaticExample.class)\npublic class VerifyZeroInteractionsTest {\n    \n    @Test\n    public void should_throw_verification_exception_in_case_if_static_method_is_called() {\n        mockStatic(StaticExample.class);\n        \n        StaticExample.staticMethodReturningString();\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                verifyZeroInteractions(StaticExample.class);\n            }\n        }).as(\"Verify Exception is thrown.\")\n          .isInstanceOf(NoInteractionsWanted.class)\n          .hasMessageContaining(\"No interactions\");\n    }\n    \n    @Test\n    public void should_throw_verification_exception_in_case_if_instance_method_called() {\n        final Service mock = mock(Service.class);\n        \n        mock.getServiceMessage();\n        \n        assertThatThrownBy(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                verifyZeroInteractions(mock);\n            }\n        }).as(\"Verify Exception is thrown.\")\n          .isInstanceOf(NoInteractionsWanted.class)\n          .hasMessageContaining(\"No interactions\");\n    }\n    \n    @Test\n    public void should_not_throw_verification_exception_in_case_if_no_methods_are_called_for_static_mock() {\n        mockStatic(StaticExample.class);\n        \n        final Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                verifyZeroInteractions(StaticExample.class);\n            }\n        });\n        \n        assertThat(throwable)\n            .as(\"Verify Exception is not thrown.\")\n            .isNull();\n    }\n    \n    @Test\n    public void should_not_throw_verification_exception_in_case_if_no_methods_are_called_for_instance_mock() {\n        final Service mock = mock(Service.class);\n    \n        final Throwable throwable = catchThrowable(new ThrowingCallable() {\n            @Override\n            public void call() throws Throwable {\n                verifyZeroInteractions(mock);\n            }\n        });\n    \n        assertThat(throwable)\n            .as(\"Verify Exception is not thrown.\")\n            .isNull();\n    }\n    \n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/DoesntSupportCreatingMocksInFieldsWhenNewDefect.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.whennew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.newmocking.NewDemo;\nimport samples.newmocking.SomeDependency;\n\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.whenNew;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { \tNewDemo.class })\n/*\n  Issue <a href=\"298\">http://code.google.com/p/powermock/issues/detail?id=298</a>\n */\npublic class DoesntSupportCreatingMocksInFieldsWhenNewDefect {\n\n\tfinal SomeDependency somethingUsedByMethodUnderTest=mock(SomeDependency.class); // for some reason the mocking only works if loadingPool is a local variable not a field (like all the other mocks)\n\n\t@Test\n\tpublic void methodUnderTestShouldWorkWithClassLevelMock() throws Exception {\n\n\t\twhenNew(SomeDependency.class).withNoArguments().thenReturn(somethingUsedByMethodUnderTest);\n\n\t\tNewDemo objectUnderTest = new NewDemo();\n\t\t\n\t\tobjectUnderTest.methodUnderTest();\n\t\t\n\t}\n\n\n\t\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/NewFileExampleTest.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.whennew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.NewFileExample;\n\nimport java.io.File;\n\nimport static org.junit.Assert.assertTrue;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(NewFileExample.class)\npublic class NewFileExampleTest {\n    @Test\n    public void assertThatMockingFileWorks() throws Exception {\n        final String directoryPath = \"mocked path\";\n\n        File directoryMock = mock(File.class);\n\n        whenNew(File.class).withArguments(directoryPath).thenReturn(directoryMock);\n        when(directoryMock.exists()).thenReturn(false);\n        when(directoryMock.mkdirs()).thenReturn(true);\n\n        assertTrue(new NewFileExample().createDirectoryStructure(directoryPath));\n\n        verifyNew(File.class).withArguments(directoryPath);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewMultipleTimesTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.whennew;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.NewFileExample;\n\nimport java.io.File;\n\nimport static org.junit.Assert.assertTrue;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest(NewFileExample.class)\npublic class VerifyNewMultipleTimesTest {\n    private final static String DIRECTORY_PATH = \"mocked path\";\n    @Mock\n    private File directoryMock;\n\n    @Before\n    public void setUp() throws Exception {\n        MockitoAnnotations.initMocks(this);\n\n        whenNew(File.class).withArguments(DIRECTORY_PATH).thenReturn(directoryMock);\n\n        when(directoryMock.exists()).thenReturn(false);\n        when(directoryMock.mkdirs()).thenReturn(true);\n    }\n\n    @Test(expected=AssertionError.class)\n    public void verifyNewTooManyTimesCausesAssertionError() throws Exception {\n        assertTrue(new NewFileExample().createDirectoryStructure((DIRECTORY_PATH)));\n\n        verify(directoryMock).mkdirs();\n\n        // Correct usage\n        verifyNew(File.class, times(1)).withArguments(DIRECTORY_PATH);\n\n        // Should throw\n        verifyNew(File.class, times(100000)).withArguments(DIRECTORY_PATH);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewWithoutWhenNewTest.java",
    "content": "package samples.powermockito.junit4.whennew;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.mockito.PowerMockito.verifyNew;\n\n@PrepareForTest(ExpectNewDemo.class)\n@RunWith(PowerMockRunner.class)\npublic class VerifyNewWithoutWhenNewTest {\n\n    @Test\n    public void verifyingNewWithoutExpectationWhenNoArgumentsThrowsISE() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        assertEquals(\"Hello world\", tested.getMessage());\n\n        try {\n            verifyNew(MyClass.class).withNoArguments();\n            fail(\"IllegalStateException expected\");\n        } catch (IllegalArgumentException e) {\n            assertEquals(\"No instantiation of class samples.newmocking.MyClass was recorded \"\n                    + \"during the test. Note that only expected object creations \"\n                    + \"(e.g. those using whenNew(..)) can be verified.\", e.getMessage());\n        }\n\n    }\n\n    @Test\n    public void verifyingNewWithoutExpectationButWithArgumentsThrowsISE() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        assertEquals(\"Hello world\", tested.getMessage());\n\n        try {\n            verifyNew(MyClass.class, Mockito.atLeastOnce()).withNoArguments();\n            fail(\"IllegalStateException expected\");\n        } catch (IllegalArgumentException e) {\n            assertEquals(\"No instantiation of class samples.newmocking.MyClass was recorded \"\n                    + \"during the test. Note that only expected object creations \"\n                    + \"(e.g. those using whenNew(..)) can be verified.\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.whennew;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport samples.Service;\nimport samples.classwithinnermembers.ClassWithInnerMembers;\nimport samples.classwithinnermembers.ClassWithInnerMembers.*;\nimport samples.expectnew.CreationException;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.expectnew.ExpectNewServiceUser;\nimport samples.expectnew.ExpectNewWithMultipleCtorDemo;\nimport samples.expectnew.ITarget;\nimport samples.expectnew.MultiConstructor;\nimport samples.expectnew.SimpleVarArgsConstructorDemo;\nimport samples.expectnew.Target;\nimport samples.expectnew.VarArgsConstructorDemo;\nimport samples.newmocking.MyClass;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertSame;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.Mockito.atLeastOnce;\nimport static org.mockito.Mockito.doNothing;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\n\n/**\n * Test class to demonstrate new instance mocking using whenConstructionOf(..).\n */\n@PrepareForTest({MyClass.class, ExpectNewDemo.class, ClassWithInnerMembers.class, DataInputStream.class,\n        WhenNewCases.class, Target.class, MultiConstructor.class})\npublic class WhenNewCases {\n\n    public static final String TARGET_NAME = \"MyTarget\";\n    public static final int TARGET_ID = 1;\n    public static final String UNKNOWN_TARGET_NAME = \"Unknown2\";\n    public static final int UNKNOWN_TARGET_ID = -11;\n    @Rule\n    public ExpectedException expectedException = ExpectedException.none();\n\n    @Test\n    public void testStaticMemberClassMockingWorksWithNoConstructorArguments() throws Exception {\n        Class<Object> innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, \"MyInnerClass\");\n        Object mockMyInnerClass = mock(innerClassType);\n        whenNew(innerClassType).withNoArguments().thenReturn(mockMyInnerClass);\n        doReturn(\"something else\").when(mockMyInnerClass, \"doStuff\");\n\n        assertEquals(\"something else\", new ClassWithInnerMembers().getValue());\n    }\n\n    @Test\n    public void testStaticMemberClassMockingWorksWithConstructorArguments() throws Exception {\n        Class<Object> innerClassType = Whitebox.getInnerClassType(\n                ClassWithInnerMembers.class, \"StaticInnerClassWithConstructorArgument\");\n        Object mockMyInnerClass = mock(innerClassType);\n        whenNew(innerClassType).withArguments(\"value\").thenReturn(mockMyInnerClass);\n        doReturn(\"something else\").when(mockMyInnerClass, \"doStuff\");\n\n        assertEquals(\n                \"something else\", new ClassWithInnerMembers().getValueForStaticInnerClassWithConstructorArgument());\n    }\n\n    @Test\n    public void testLocalClassMockingWorksWithNoConstructorArguments() throws Exception {\n        Class<Object> innerClassType = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 1, \"MyLocalClass\");\n        Object mockMyInnerClass = mock(innerClassType);\n        whenNew(innerClassType).withNoArguments().thenReturn(mockMyInnerClass);\n        doReturn(\"something else\").when(mockMyInnerClass, \"doStuff\");\n\n        assertEquals(\"something else\", new ClassWithInnerMembers().getLocalClassValue());\n    }\n\n    @Test\n    public void testLocalClassMockingWorksWithConstructorArguments() throws Exception {\n        Class<Object> innerClassType = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 2, \"MyLocalClass\");\n        Object mockMyInnerClass = mock(innerClassType);\n        whenNew(innerClassType).withArguments(\"my value\").thenReturn(mockMyInnerClass);\n        doReturn(\"something else\").when(mockMyInnerClass, \"doStuff\");\n\n        assertEquals(\"something else\", new ClassWithInnerMembers().getLocalClassValueWithArgument());\n    }\n\n    @Test\n    public void testNonStaticMemberClassMockingWorksWithArguments() throws Exception {\n        Class<Object> innerClassType = Whitebox.getInnerClassType(\n                ClassWithInnerMembers.class, \"MyInnerClassWithConstructorArgument\");\n        Object mockMyInnerClass = mock(innerClassType);\n        whenNew(innerClassType).withArguments(\"value\").thenReturn(mockMyInnerClass);\n        doReturn(\"something else\").when(mockMyInnerClass, \"doStuff\");\n\n        assertEquals(\"something else\", new ClassWithInnerMembers().getValueForInnerClassWithConstructorArgument());\n    }\n\n    @Test\n    public void testNewInnerWithDiffParams() throws Exception {\n        ClassWithInnerMembers outerClass = new ClassWithInnerMembers();\n        MyInnerClassWithPrivateConstructorWithDiffMultArgs mockMyInnerClassWithPrivateConstructorWithDiffMultArgs\n                = mock(MyInnerClassWithPrivateConstructorWithDiffMultArgs.class);\n\n        whenNew(MyInnerClassWithPrivateConstructorWithDiffMultArgs.class)\n                .withArguments(null, 2, \"3\").thenReturn(mockMyInnerClassWithPrivateConstructorWithDiffMultArgs);\n\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPrivateConstructorWithDiffMultArgs,\n                outerClass.makeMyInnerClassWithPrivateConstructorWithDiffMultArgs(null, 2, \"3\"));\n    }\n\n    @Test\n    public void testNewInnerWithNoNullParams() throws Exception {\n        ClassWithInnerMembers outerClass = new ClassWithInnerMembers();\n        MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs\n                = mock(MyInnerClassWithPublicConstructorWithMultArgs.class);\n        MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs\n                = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class);\n        MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs\n                = mock(MyInnerClassWithPackageConstructorWithMultArgs.class);\n        MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs\n                = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class);\n\n        whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", \"3\").thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs);\n        whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", \"3\").thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", \"3\").thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", \"3\").thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs);\n\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPublicConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs(\"1\", \"2\", \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithProtectedConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs(\"1\", \"2\", \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPackageConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs(\"1\", \"2\", \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPrivateConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs(\"1\", \"2\", \"3\"));\n    }\n\n    @Test\n    public void testNewInnerWithMiddleParamNull() throws Exception {\n        ClassWithInnerMembers outerClass = new ClassWithInnerMembers();\n        MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs\n                = mock(MyInnerClassWithPublicConstructorWithMultArgs.class);\n        MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs\n                = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class);\n        MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs\n                = mock(MyInnerClassWithPackageConstructorWithMultArgs.class);\n        MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs\n                = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class);\n\n        whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class)\n                .withArguments(\"1\", null, \"3\").thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs);\n        whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class)\n                .withArguments(\"1\", null, \"3\").thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class)\n                .withArguments(\"1\", null, \"3\").thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class)\n                .withArguments(\"1\", null, \"3\").thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs);\n\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPublicConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs(\"1\", null, \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithProtectedConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs(\"1\", null, \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPackageConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs(\"1\", null, \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPrivateConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs(\"1\", null, \"3\"));\n    }\n\n    @Test\n    public void testNewInnerWithFirstParamNull() throws Exception {\n        ClassWithInnerMembers outerClass = new ClassWithInnerMembers();\n        MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs\n                = mock(MyInnerClassWithPublicConstructorWithMultArgs.class);\n        MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs\n                = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class);\n        MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs\n                = mock(MyInnerClassWithPackageConstructorWithMultArgs.class);\n        MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs\n                = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class);\n\n        whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class)\n                .withArguments(null, \"2\", \"3\").thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs);\n        whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class)\n                .withArguments(null, \"2\", \"3\").thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class)\n                .withArguments(null, \"2\", \"3\").thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class)\n                .withArguments(null, \"2\", \"3\").thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs);\n\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPublicConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs(null, \"2\", \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithProtectedConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs(null, \"2\", \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPackageConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs(null, \"2\", \"3\"));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPrivateConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs(null, \"2\", \"3\"));\n    }\n\n    @Test\n    public void testNewInnerWithLastParamNull() throws Exception {\n        ClassWithInnerMembers outerClass = new ClassWithInnerMembers();\n        MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs\n                = mock(MyInnerClassWithPublicConstructorWithMultArgs.class);\n        MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs\n                = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class);\n        MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs\n                = mock(MyInnerClassWithPackageConstructorWithMultArgs.class);\n        MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs\n                = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class);\n\n        whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", null).thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs);\n        whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", null).thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", null).thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs);\n        whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class)\n                .withArguments(\"1\", \"2\", null).thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs);\n\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPublicConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs(\"1\", \"2\", null));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithProtectedConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs(\"1\", \"2\", null));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPackageConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs(\"1\", \"2\", null));\n        assertEquals(\"Expected and actual did not match\", mockMyInnerClassWithPrivateConstructorWithMultArgs,\n                outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs(\"1\", \"2\", null));\n    }\n\n    @Test\n    public void testNewWithCheckedException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing checked exception\";\n        whenNew(MyClass.class).withNoArguments().thenThrow(new IOException(expectedFailMessage));\n\n        try {\n            tested.throwExceptionAndWrapInRunTimeWhenInvoction();\n            fail(\"Should throw a checked Exception!\");\n        } catch (RuntimeException e) {\n            assertTrue(e.getCause() instanceof IOException);\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testGetMessage() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        when(myClassMock.getMessage()).thenReturn(\"Hello altered World\");\n\n        String actual = tested.getMessage();\n\n        verify(myClassMock).getMessage();\n        verifyNew(MyClass.class).withNoArguments();\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testGetMessageWithArgument() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        when(myClassMock.getMessage(\"test\")).thenReturn(\"Hello altered World\");\n\n        String actual = tested.getMessageWithArgument();\n\n        verify(myClassMock).getMessage(\"test\");\n        verifyNew(MyClass.class).withNoArguments();\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testInvokeVoidMethod() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        doNothing().when(myClassMock).voidMethod();\n\n        tested.invokeVoidMethod();\n\n        verify(myClassMock).voidMethod();\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testNewWithRuntimeException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing\";\n        whenNew(MyClass.class).withNoArguments().thenThrow(new RuntimeException(expectedFailMessage));\n\n        try {\n            tested.throwExceptionWhenInvoction();\n            fail(\"Should throw RuntimeException!\");\n        } catch (RuntimeException e) {\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        when(myClassMock.getMessage()).thenReturn(\"Hello\");\n\n        final String actual = tested.multipleNew();\n\n        verify(myClassMock, times(2)).getMessage();\n        verifyNew(MyClass.class, times(2)).withNoArguments();\n\n        assertEquals(\"HelloHello\", actual);\n    }\n\n    @Test\n    public void testSimpleMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        tested.simpleMultipleNew();\n\n        verifyNew(MyClass.class, times(3)).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        tested.simpleMultipleNew();\n\n        try {\n            verifyNew(MyClass.class, times(4)).withNoArguments();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 4 times but was 3 times.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleMultipleNew();\n        try {\n            verifyNew(MyClass.class, times(1)).withNoArguments();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 1 time but was 3 times.\", e.getMessage());\n        }\n    }\n\n    /**\n     * Verifies that the issue\n     * http://code.google.com/p/powermock/issues/detail?id=10 is solved.\n     */\n    @Test\n    public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n\n        try {\n            verifyNew(MyClass.class, times(2)).withNoArguments();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 2 times but was 3 times.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_ok() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n\n        verifyNew(MyClass.class, times(3)).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleSingleNew_withOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleSingleNew();\n\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleSingleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleSingleNew();\n\n        verifyNew(MyClass.class, atLeastOnce()).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleMultipleNew();\n\n        verifyNew(MyClass.class, atLeastOnce()).withNoArguments();\n    }\n\n    //\n    @Test\n    public void testAlternativeFlow() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        whenNew(DataInputStream.class).withArguments(null).thenThrow(new RuntimeException(\"error\"));\n\n        InputStream stream = tested.alternativePath();\n\n        verifyNew(DataInputStream.class).withArguments(null);\n\n        assertNotNull(\"The returned inputstream should not be null.\", stream);\n        assertTrue(\"The returned inputstream should be an instance of ByteArrayInputStream.\",\n                   stream instanceof ByteArrayInputStream);\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n        try {\n            verifyNew(MyClass.class, times(4)).withNoArguments();\n            fail(\"Should throw an exception!.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 4 times but was 3 times.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn(\n                expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewWithParameterTypesAndArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewServiceUser.class).withParameterTypes(Service.class, int.class)\n                                           .withArguments(serviceMock, numberOfTimes)\n                                           .thenReturn(expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewWithConstructorUsingParameterTypesAndArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(constructor(ExpectNewServiceUser.class, Service.class, int.class)).withArguments(serviceMock,\n                                                                                                 numberOfTimes)\n                                                                                  .thenReturn(expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewUsingConstructorWithArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(constructor(ExpectNewServiceUser.class)).withArguments(serviceMock, numberOfTimes).thenReturn(\n                expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewWithVarArgs() throws Exception {\n        final String firstString = \"hello\";\n        final String secondString = \"world\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        whenNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getAllMessages()).thenReturn(new String[]{firstString, secondString});\n\n        String[] varArgs = tested.newVarArgs(firstString, secondString);\n        assertEquals(2, varArgs.length);\n        assertEquals(firstString, varArgs[0]);\n        assertEquals(secondString, varArgs[1]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString);\n    }\n\n    @Test\n    public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception {\n        final Object object = new Object();\n        try {\n            whenNew(VarArgsConstructorDemo.class).withArguments(object);\n            fail(\"Should throw ConstructorNotFoundException!\");\n        } catch (ConstructorNotFoundException e) {\n            assertEquals(\"No constructor found in class '\" + VarArgsConstructorDemo.class.getName()\n                                 + \"' with parameter types: [ \" + object.getClass().getName() + \" ].\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        Service serviceMock = mock(Service.class);\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final Service serviceSubTypeInstance = new Service() {\n\n            public String getServiceMessage() {\n                return \"message\";\n            }\n        };\n\n        whenNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getAllServices()).thenReturn(new Service[]{serviceMock});\n\n        Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock);\n        assertEquals(1, varArgs.length);\n        assertSame(serviceMock, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgs() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[]{42};\n        final byte[] byteArrayTwo = new byte[]{17};\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsAndMatchers() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[]{42};\n        final byte[] byteArrayTwo = new byte[]{17};\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne});\n\n        byte[][] varArgs = tested.newVarArgsWithMatchers();\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[]{17};\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[]{42};\n        final byte[] byteArrayTwo = null;\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull()\n            throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[]{42};\n        final byte[] byteArrayThree = null;\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenAllArgumentsAreNullAndOverloadedVarArgsConstructors() throws Exception {\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = null;\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{ byteArrayTwo});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        SimpleVarArgsConstructorDemo varArgsConstructorDemoMock = mock(SimpleVarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = null;\n        whenNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo});\n\n        byte[][] varArgs = tested.newSimpleVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test(expected = NullPointerException.class)\n    public void testNewWithWrongArgument() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn(\n                expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n        /*\n         * Should throw NPE because the default behavior of Mockito when a\n         * something isn't expected is to return a default value. In this case\n         * whenConstructionOf\n         * (ExpectNewServiceUser.class).withArguments(serviceMock,\n         * numberOfTimes) is the wrong expectation and thus null is returned\n         * from the substitute mock which is the correct behavior.\n         */\n        fail(\"Should throw NPE!\");\n    }\n\n    @Test\n    public void testExpectNewButNoNewCallWasMade() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.makeDate();\n\n        try {\n            verifyNew(MyClass.class).withNoArguments();\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\n                    \"Wanted but not invoked samples.newmocking.MyClass();\\nActually, there were zero interactions with this mock.\",\n                    e.getMessage());\n        }\n    }\n\n\n    @Test\n    public void whenNewSupportsVarArgsAsSecondParameter() throws Exception {\n        final int one = 1;\n        final int two = 2;\n        final float myFloat = 3.0f;\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        whenNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two).thenReturn(varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getInts()).thenReturn(new int[] { one, two});\n\n        int[] varArgs = tested.newVarArgs(myFloat, one, two);\n        assertEquals(2, varArgs.length);\n        assertEquals(one, varArgs[0]);\n        assertEquals(two, varArgs[1]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two);\n    }\n\n    @Test\n    public void whenNewAnyArgumentsWorksInClassesWithSingleCtor() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withAnyArguments().thenReturn(myClassMock);\n\n        when(myClassMock.getMessage()).thenReturn(\"Hello\");\n\n        final String actual = tested.multipleNew();\n\n        verify(myClassMock, times(2)).getMessage();\n        verifyNew(MyClass.class, times(2)).withNoArguments();\n\n        assertEquals(\"HelloHello\", actual);\n    }\n\n    @Test\n    public void whenNewAnyArgumentsWorksInClassesWithMultipleCtors() throws Exception {\n        ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemoMock = mock(ExpectNewWithMultipleCtorDemo.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewWithMultipleCtorDemo.class).withAnyArguments().thenReturn(expectNewWithMultipleCtorDemoMock);\n        when(expectNewWithMultipleCtorDemoMock.useService()).thenReturn(\"message\");\n\n        // When\n        final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo = new ExpectNewWithMultipleCtorDemo(serviceMock);\n        final String message1 = expectNewWithMultipleCtorDemo.useService();\n        final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo1 = new ExpectNewWithMultipleCtorDemo(serviceMock, 5);\n        final String message2 = expectNewWithMultipleCtorDemo1.useService();\n\n\n        assertEquals(message1, \"message\");\n        assertEquals(message2, \"message\");\n    }\n\n    @Test\n    public void canDefineSeveralMockResultForNew() throws Exception {\n\n        final Target expectedTarget = new Target(UNKNOWN_TARGET_NAME,UNKNOWN_TARGET_ID);\n\n        whenNew(Target.class).withArguments(eq(TARGET_NAME),eq(TARGET_ID)).thenThrow(new CreationException());\n        whenNew(Target.class).withArguments(eq(\"Unknown\"), eq(-1)).thenReturn(expectedTarget);\n\n        Target actualTarget = new ExpectNewDemo().createTarget(new ITarget() {\n            @Override\n            public int getId() {\n                return TARGET_ID;\n            }\n\n            @Override\n            public String getName() {\n                return TARGET_NAME;\n            }\n        });\n        assertThat(actualTarget).isEqualToComparingFieldByField(expectedTarget);\n    }\n\n    @Test\n    public void multiConstructorMatching() throws Exception {\n\n        MultiConstructor expectedObject = new MultiConstructor(\"only\");\n\n        whenNew(MultiConstructor.class).withAnyArguments().thenReturn(expectedObject);\n\n        MultiConstructor actualObject = new MultiConstructor(null);\n        assertNotNull(\"withAnyArguments did not match constructor(String=null)\", actualObject);\n        assertEquals(\"only\", actualObject.getFirst());\n\n        actualObject = new MultiConstructor(\"first\", null);\n        assertNotNull(\"withAnyArguments did not match constructor(String, String=null)\", actualObject);\n        assertEquals(\"only\", actualObject.getFirst());\n\n        actualObject = new MultiConstructor(\"first\", null, true);\n        assertNotNull(\"withAnyArguments did not match constructor(Runnable=null, boolean, Object)\", actualObject);\n        assertEquals(\"only\", actualObject.getFirst());\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java.orig",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.whennew;\n\nimport org.junit.Rule;\nimport org.junit.Test;\n<<<<<<< HEAD:modules/module-test/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java\nimport org.junit.rules.ExpectedException;\n=======\nimport org.junit.runner.RunWith;\nimport org.mockito.runners.MockitoJUnitRunner;\n>>>>>>> Finish gradle migration for building project. next step create release.:modules/module-test/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCases.java\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport org.powermock.reflect.Whitebox;\nimport org.powermock.reflect.exceptions.ConstructorNotFoundException;\nimport samples.Service;\nimport samples.expectnew.CreationException;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.expectnew.ExpectNewServiceUser;\nimport samples.expectnew.ExpectNewWithMultipleCtorDemo;\nimport samples.expectnew.ITarget;\nimport samples.expectnew.SimpleVarArgsConstructorDemo;\nimport samples.expectnew.Target;\nimport samples.expectnew.VarArgsConstructorDemo;\nimport samples.newmocking.MyClass;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertSame;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.atLeastOnce;\nimport static org.mockito.Mockito.doNothing;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.verifyNew;\nimport static org.powermock.api.mockito.PowerMockito.when;\nimport static org.powermock.api.mockito.PowerMockito.whenNew;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\n\n/**\n * Test class to demonstrate new instance mocking using whenConstructionOf(..).\n */\n<<<<<<< HEAD:modules/module-test/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java\n@PrepareForTest({MyClass.class, ExpectNewDemo.class, DataInputStream.class, WhenNewCases.class, Target.class})\n=======\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(MockitoJUnitRunner.class)\n@PrepareForTest({MyClass.class, ExpectNewDemo.class, DataInputStream.class})\n>>>>>>> Finish gradle migration for building project. next step create release.:modules/module-test/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCases.java\npublic class WhenNewCases {\n\n    public static final String TARGET_NAME = \"MyTarget\";\n    public static final int TARGET_ID = 1;\n    public static final String UNKNOWN_TARGET_NAME = \"Unknown2\";\n    public static final int UNKNOWN_TARGET_ID = -11;\n    @Rule\n    public ExpectedException expectedException = ExpectedException.none();\n\n    @Test\n    public void testNewWithCheckedException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing checked exception\";\n        whenNew(MyClass.class).withNoArguments().thenThrow(new IOException(expectedFailMessage));\n\n        try {\n            tested.throwExceptionAndWrapInRunTimeWhenInvoction();\n            fail(\"Should throw a checked Exception!\");\n        } catch (RuntimeException e) {\n            assertTrue(e.getCause() instanceof IOException);\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testGetMessage() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        when(myClassMock.getMessage()).thenReturn(\"Hello altered World\");\n\n        String actual = tested.getMessage();\n\n        verify(myClassMock).getMessage();\n        verifyNew(MyClass.class).withNoArguments();\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testGetMessageWithArgument() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        String expected = \"Hello altered World\";\n        when(myClassMock.getMessage(\"test\")).thenReturn(\"Hello altered World\");\n\n        String actual = tested.getMessageWithArgument();\n\n        verify(myClassMock).getMessage(\"test\");\n        verifyNew(MyClass.class).withNoArguments();\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void testInvokeVoidMethod() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        doNothing().when(myClassMock).voidMethod();\n\n        tested.invokeVoidMethod();\n\n        verify(myClassMock).voidMethod();\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testNewWithRuntimeException() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        final String expectedFailMessage = \"testing\";\n        whenNew(MyClass.class).withNoArguments().thenThrow(new RuntimeException(expectedFailMessage));\n\n        try {\n            tested.throwExceptionWhenInvoction();\n            fail(\"Should throw RuntimeException!\");\n        } catch (RuntimeException e) {\n            assertEquals(expectedFailMessage, e.getMessage());\n        }\n\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        when(myClassMock.getMessage()).thenReturn(\"Hello\");\n\n        final String actual = tested.multipleNew();\n\n        verify(myClassMock, times(2)).getMessage();\n        verifyNew(MyClass.class, times(2)).withNoArguments();\n\n        assertEquals(\"HelloHello\", actual);\n    }\n\n    @Test\n    public void testSimpleMultipleNew() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        tested.simpleMultipleNew();\n\n        verifyNew(MyClass.class, times(3)).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock);\n\n        tested.simpleMultipleNew();\n\n        try {\n            verifyNew(MyClass.class, times(4)).withNoArguments();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 4 times but was 3 times.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleMultipleNew();\n        try {\n            verifyNew(MyClass.class, times(1)).withNoArguments();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 1 time but was 3 times.\", e.getMessage());\n        }\n    }\n\n    /**\n     * Verifies that the issue\n     * http://code.google.com/p/powermock/issues/detail?id=10 is solved.\n     */\n    @Test\n    public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n\n        try {\n            verifyNew(MyClass.class, times(2)).withNoArguments();\n            fail(\"Should throw AssertionError.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 2 times but was 3 times.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_ok() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n\n        verifyNew(MyClass.class, times(3)).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleSingleNew_withOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleSingleNew();\n\n        verifyNew(MyClass.class).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleSingleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleSingleNew();\n\n        verifyNew(MyClass.class, atLeastOnce()).withNoArguments();\n    }\n\n    @Test\n    public void testSimpleMultipleNew_withAtLeastOnce() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.simpleMultipleNew();\n\n        verifyNew(MyClass.class, atLeastOnce()).withNoArguments();\n    }\n\n    //\n    @Test\n    public void testAlternativeFlow() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        whenNew(DataInputStream.class).withArguments(null).thenThrow(new RuntimeException(\"error\"));\n\n        InputStream stream = tested.alternativePath();\n\n        verifyNew(DataInputStream.class).withArguments(null);\n\n        assertNotNull(\"The returned inputstream should not be null.\", stream);\n        assertTrue(\"The returned inputstream should be an instance of ByteArrayInputStream.\",\n                   stream instanceof ByteArrayInputStream);\n    }\n\n    @Test\n    public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        Whitebox.invokeMethod(tested, \"simpleMultipleNewPrivate\");\n        try {\n            verifyNew(MyClass.class, times(4)).withNoArguments();\n            fail(\"Should throw an exception!.\");\n        } catch (AssertionError e) {\n            assertEquals(\"samples.newmocking.MyClass();\\nWanted 4 times but was 3 times.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn(\n                expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewWithParameterTypesAndArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewServiceUser.class).withParameterTypes(Service.class, int.class)\n                                           .withArguments(serviceMock, numberOfTimes)\n                                           .thenReturn(expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewWithConstructorUsingParameterTypesAndArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(constructor(ExpectNewServiceUser.class, Service.class, int.class)).withArguments(serviceMock,\n                                                                                                 numberOfTimes)\n                                                                                  .thenReturn(expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewUsingConstructorWithArguments() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(constructor(ExpectNewServiceUser.class)).withArguments(serviceMock, numberOfTimes).thenReturn(\n                expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n    }\n\n    @Test\n    public void testNewWithVarArgs() throws Exception {\n        final String firstString = \"hello\";\n        final String secondString = \"world\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        whenNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getAllMessages()).thenReturn(new String[]{firstString, secondString});\n\n        String[] varArgs = tested.newVarArgs(firstString, secondString);\n        assertEquals(2, varArgs.length);\n        assertEquals(firstString, varArgs[0]);\n        assertEquals(secondString, varArgs[1]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString);\n    }\n\n    @Test\n    public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception {\n        final Object object = new Object();\n        try {\n            whenNew(VarArgsConstructorDemo.class).withArguments(object);\n            fail(\"Should throw ConstructorNotFoundException!\");\n        } catch (ConstructorNotFoundException e) {\n            assertEquals(\"No constructor found in class '\" + VarArgsConstructorDemo.class.getName()\n                                 + \"' with parameter types: [ \" + object.getClass().getName() + \" ].\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        Service serviceMock = mock(Service.class);\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final Service serviceSubTypeInstance = new Service() {\n\n            public String getServiceMessage() {\n                return \"message\";\n            }\n        };\n\n        whenNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getAllServices()).thenReturn(new Service[]{serviceMock});\n\n        Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock);\n        assertEquals(1, varArgs.length);\n        assertSame(serviceMock, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgs() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[]{42};\n        final byte[] byteArrayTwo = new byte[]{17};\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsAndMatchers() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[]{42};\n        final byte[] byteArrayTwo = new byte[]{17};\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne});\n\n        byte[][] varArgs = tested.newVarArgsWithMatchers();\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[]{17};\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = new byte[]{42};\n        final byte[] byteArrayTwo = null;\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayOne, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull()\n            throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = new byte[]{42};\n        final byte[] byteArrayThree = null;\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree);\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenAllArgumentsAreNullAndOverloadedVarArgsConstructors() throws Exception {\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = null;\n        whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{ byteArrayTwo});\n\n        byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n\n    }\n\n    @Test\n    public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n        SimpleVarArgsConstructorDemo varArgsConstructorDemoMock = mock(SimpleVarArgsConstructorDemo.class);\n\n        final byte[] byteArrayOne = null;\n        final byte[] byteArrayTwo = null;\n        whenNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn(\n                varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo});\n\n        byte[][] varArgs = tested.newSimpleVarArgs(byteArrayOne, byteArrayTwo);\n        assertEquals(1, varArgs.length);\n        assertSame(byteArrayTwo, varArgs[0]);\n\n        verifyNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo);\n    }\n\n    @Test(expected = NullPointerException.class)\n    public void testNewWithWrongArgument() throws Exception {\n        final int numberOfTimes = 2;\n        final String expected = \"used\";\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn(\n                expectNewServiceImplMock);\n        when(expectNewServiceImplMock.useService()).thenReturn(expected);\n\n        assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes));\n\n        verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes);\n        /*\n         * Should throw NPE because the default behavior of Mockito when a\n         * something isn't expected is to return a default value. In this case\n         * whenConstructionOf\n         * (ExpectNewServiceUser.class).withArguments(serviceMock,\n         * numberOfTimes) is the wrong expectation and thus null is returned\n         * from the substitute mock which is the correct behavior.\n         */\n        fail(\"Should throw NPE!\");\n    }\n\n    @Test\n    public void testExpectNewButNoNewCallWasMade() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock1 = mock(MyClass.class);\n\n        whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1);\n\n        tested.makeDate();\n\n        try {\n            verifyNew(MyClass.class).withNoArguments();\n            fail(\"Should throw AssertionError!\");\n        } catch (AssertionError e) {\n            assertEquals(\n                    \"Wanted but not invoked samples.newmocking.MyClass();\\nActually, there were zero interactions with this mock.\",\n                    e.getMessage());\n        }\n    }\n\n\n    @Test\n    public void whenNewSupportsVarArgsAsSecondParameter() throws Exception {\n        final int one = 1;\n        final int two = 2;\n        final float myFloat = 3.0f;\n\n        ExpectNewDemo tested = new ExpectNewDemo();\n        VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class);\n\n        whenNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two).thenReturn(varArgsConstructorDemoMock);\n        when(varArgsConstructorDemoMock.getInts()).thenReturn(new int[] { one, two});\n\n        int[] varArgs = tested.newVarArgs(myFloat, one, two);\n        assertEquals(2, varArgs.length);\n        assertEquals(one, varArgs[0]);\n        assertEquals(two, varArgs[1]);\n\n        verifyNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two);\n    }\n\n    @Test\n    public void whenNewAnyArgumentsWorksInClassesWithSingleCtor() throws Exception {\n        ExpectNewDemo tested = new ExpectNewDemo();\n\n        MyClass myClassMock = mock(MyClass.class);\n\n        whenNew(MyClass.class).withAnyArguments().thenReturn(myClassMock);\n\n        when(myClassMock.getMessage()).thenReturn(\"Hello\");\n\n        final String actual = tested.multipleNew();\n\n        verify(myClassMock, times(2)).getMessage();\n        verifyNew(MyClass.class, times(2)).withNoArguments();\n\n        assertEquals(\"HelloHello\", actual);\n    }\n\n    @Test\n    public void whenNewAnyArgumentsWorksInClassesWithMultipleCtors() throws Exception {\n        ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemoMock = mock(ExpectNewWithMultipleCtorDemo.class);\n        Service serviceMock = mock(Service.class);\n\n        whenNew(ExpectNewWithMultipleCtorDemo.class).withAnyArguments().thenReturn(expectNewWithMultipleCtorDemoMock);\n        when(expectNewWithMultipleCtorDemoMock.useService()).thenReturn(\"message\");\n\n        // When\n        final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo = new ExpectNewWithMultipleCtorDemo(serviceMock);\n        final String message1 = expectNewWithMultipleCtorDemo.useService();\n        final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo1 = new ExpectNewWithMultipleCtorDemo(serviceMock, 5);\n        final String message2 = expectNewWithMultipleCtorDemo1.useService();\n\n\n        assertEquals(message1, \"message\");\n        assertEquals(message2, \"message\");\n    }\n\n    @Test\n    public void canDefineSeveralMockResultForNew() throws Exception {\n\n        final Target expectedTarget = new Target(UNKNOWN_TARGET_NAME,UNKNOWN_TARGET_ID);\n\n        whenNew(Target.class).withArguments(eq(TARGET_NAME),eq(TARGET_ID)).thenThrow(new CreationException());\n        whenNew(Target.class).withArguments(eq(\"Unknown\"), eq(-1)).thenReturn(expectedTarget);\n\n        Target actualTarget = new ExpectNewDemo().createTarget(new ITarget() {\n            @Override\n            public int getId() {\n                return TARGET_ID;\n            }\n\n            @Override\n            public String getName() {\n                return TARGET_NAME;\n            }\n        });\n        assertThat(actualTarget).isEqualToComparingFieldByField(expectedTarget);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.whennew;\n\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\n/**\n * Test class to demonstrate new instance mocking using whenConstructionOf(..).\n *\n */\n@RunWith(PowerMockRunner.class)\npublic class WhenNewTest extends WhenNewCases {\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/java/samples/powermockito/junit4/withsettings/WithSettingsTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.withsettings;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.finalmocking.FinalDemo;\nimport samples.finalmocking.HoldingFinalDemo;\nimport samples.finalmocking.StaticHoldingFinalDemo;\n\nimport static org.junit.Assert.assertNotNull;\nimport static org.mockito.Mockito.RETURNS_MOCKS;\nimport static org.mockito.Mockito.withSettings;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\n\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { StaticHoldingFinalDemo.class, HoldingFinalDemo.class, FinalDemo.class })\npublic class WithSettingsTest {\n\n\t@Test\n\tpublic void powermockitoSupportsAnswersForInstanceMethods() {\n\t\tHoldingFinalDemo tested = mock(HoldingFinalDemo.class, RETURNS_MOCKS);\n\t\tassertNotNull(tested.getFinalDemo());\n\t}\n\n\t@Test\n\tpublic void powermockitoSupportsWithSettingsForInstanceMethods() {\n\t\tHoldingFinalDemo tested = mock(HoldingFinalDemo.class, withSettings().defaultAnswer(RETURNS_MOCKS));\n\t\tassertNotNull(tested.getFinalDemo());\n\t}\n\n\t@Test\n\tpublic void powermockitoSupportsAnswersForStaticMethods() {\n\t\tmockStatic(StaticHoldingFinalDemo.class, RETURNS_MOCKS);\n\t\tassertNotNull(StaticHoldingFinalDemo.getFinalDemo());\n\t}\n\n\t@Test\n\tpublic void powermockitoSupportsWithSettingsForStaticMethods() {\n\t\tmockStatic(StaticHoldingFinalDemo.class, withSettings().defaultAnswer(RETURNS_MOCKS));\n\t\tassertNotNull(StaticHoldingFinalDemo.getFinalDemo());\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4/src/test/resources/org/powermock/extensions/configuration.properties",
    "content": "powermock.global-ignore=samples.powermockito.junit4.bugs.github801.GlobalPowerMockIgnore"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.Service;\nimport samples.annotationbased.AnnotationDemo;\n\nimport java.util.Arrays;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n@RunWith(Parameterized.class)\npublic class AnnotationUsageTest {\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n\n\n    @InjectMocks\n    AnnotationDemo tested;\n\n\n    @Mock\n    Service server;\n\n\n    final String fooId;\n\n\n    public AnnotationUsageTest(String fooId) {\n        this.fooId = fooId;\n    }\n\n\n    @Parameterized.Parameters()\n    public static Iterable<Object[]> data() {\n        return Arrays.asList(new Object[][]{\n                {\"1\"},\n                {\"2\"}\n        });\n    }\n\n\n    @Before\n    public void setUp() throws Exception {\n        when(server.getServiceMessage()).thenReturn(fooId);\n    }\n\n\n    @Test\n    public void annotationsAreEnabledWhenUsingTheJUnitRule() throws Exception {\n        String serviceMessage = tested.getServiceMessage();\n        assertEquals(fooId, serviceMessage);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AssertPowerMockRuleDelagatesToOtherRulesTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.MethodRule;\nimport org.junit.rules.TestName;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\n\n/**\n * This test demonstrates that the PowerMockRule delegates to other rules.\n */\npublic class AssertPowerMockRuleDelagatesToOtherRulesTest {\n    private static final MyObject BEFORE = new MyObject();\n    \n    private final List<Object> objects = new LinkedList<Object>();\n    \n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n    \n    @Rule\n    public MyRule rule = new MyRule();\n    \n    @Rule\n    public TestName testName = new TestName();\n    \n    @Test\n    public void assertPowerMockRuleDelegatesToOtherRules() throws Exception {\n        \n        assertThat(this.getClass().getClassLoader()).isNotInstanceOf(MockClassLoader.class);\n        \n        assertThat(objects)\n            .hasSize(1)\n            .containsExactly(BEFORE);\n        \n        assertThat(testName.getMethodName()).isEqualTo(\"assertPowerMockRuleDelegatesToOtherRules\");\n    }\n    \n    private static class MyObject {\n        private final String state = \"state\";\n        \n        @Override\n        public int hashCode() {\n            return state.hashCode();\n        }\n        \n        @Override\n        public boolean equals(Object o) {\n            if (this == o) { return true; }\n            if (o == null || getClass() != o.getClass()) { return false; }\n            \n            MyObject myObject = (MyObject) o;\n            \n            return state.equals(myObject.state);\n        }\n    }\n    \n    private class MyRule implements MethodRule {\n        @Override\n        public Statement apply(final Statement base, FrameworkMethod method, Object target) {\n            return new Statement() {\n                @Override\n                public void evaluate() throws Throwable {\n                    objects.add(BEFORE);\n                    base.evaluate();\n                }\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java",
    "content": "package samples.powermockito.junit4.agent;\r\n\r\nimport org.junit.Rule;\r\nimport org.junit.Test;\r\nimport org.powermock.core.classloader.annotations.PrepareForTest;\r\nimport org.powermock.modules.junit4.rule.PowerMockRule;\r\nimport samples.largemethod.MethodExceedingJvmLimit;\r\n\r\nimport static junit.framework.Assert.assertEquals;\r\nimport static junit.framework.Assert.assertNull;\r\nimport static junit.framework.Assert.assertSame;\r\nimport static junit.framework.Assert.assertTrue;\r\nimport static junit.framework.Assert.fail;\r\nimport static org.mockito.Mockito.when;\r\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\r\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\r\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\r\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\r\n\r\n@PrepareForTest(MethodExceedingJvmLimit.class)\r\npublic class LargeMethodTest {\r\n\r\n    @Rule\r\n    public PowerMockRule powerMockRule = new PowerMockRule();\r\n\r\n    @Test\r\n    public void largeMethodShouldBeOverridden() {\r\n        try {\r\n            MethodExceedingJvmLimit.init();\r\n            fail(\"Method should be overridden and exception should be thrown\");\r\n        } catch (Exception e) {\r\n            assertSame(IllegalAccessException.class, e.getClass());\r\n            assertTrue(e.getMessage().contains(\"Method was too large and after instrumentation exceeded JVM limit\"));\r\n        }\r\n    }\r\n\r\n    @Test\r\n    public void largeMethodShouldBeAbleToBeSuppressed() {\r\n        suppress(method(MethodExceedingJvmLimit.class, \"init\"));\r\n        assertNull(\"Suppressed method should return: null\", MethodExceedingJvmLimit.init());\r\n    }\r\n\r\n    @Test\r\n    public void largeMethodShouldBeAbleToBeMocked() {\r\n        mockStatic(MethodExceedingJvmLimit.class);\r\n        when(MethodExceedingJvmLimit.init()).thenReturn(\"ok\");\r\n        assertEquals(\"Mocked method should return: ok\", \"ok\", MethodExceedingJvmLimit.init());\r\n        verifyStatic(MethodExceedingJvmLimit.class);\r\n        MethodExceedingJvmLimit.init();\r\n    }\r\n\r\n    @Test(expected = IllegalStateException.class)\r\n    public void largeMethodShouldBeAbleToBeMockedAndThrowException() {\r\n        mockStatic(MethodExceedingJvmLimit.class);\r\n        when(MethodExceedingJvmLimit.init()).thenThrow(new IllegalStateException());\r\n        MethodExceedingJvmLimit.init();\r\n        verifyStatic(MethodExceedingJvmLimit.class);\r\n        MethodExceedingJvmLimit.init();\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MemberModificationExampleTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.staticandinstance.StaticAndInstanceDemo;\nimport samples.suppressconstructor.SuppressConstructorHierarchy;\nimport samples.suppresseverything.SuppressEverything;\nimport samples.suppressfield.SuppressField;\nimport samples.suppressmethod.SuppressMethod;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\n\nimport static org.hamcrest.CoreMatchers.instanceOf;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructorsDeclaredIn;\nimport static org.powermock.api.support.membermodification.MemberMatcher.everythingDeclaredIn;\nimport static org.powermock.api.support.membermodification.MemberMatcher.field;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberMatcher.methods;\nimport static org.powermock.api.support.membermodification.MemberMatcher.methodsDeclaredIn;\nimport static org.powermock.api.support.membermodification.MemberModifier.replace;\nimport static org.powermock.api.support.membermodification.MemberModifier.stub;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n/**\n * Demonstrates PowerMock's ability to modify member structures.\n */\n@PrepareForTest( { SuppressMethod.class, SuppressField.class, SuppressEverything.class })\npublic class MemberModificationExampleTest {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    @Test\n    public void suppressSingleMethodExample() throws Exception {\n        suppress(method(SuppressMethod.class, \"getObject\"));\n\n        assertNull(new SuppressMethod().getObject());\n    }\n\n    @Test\n    public void suppressMultipleMethodsExample1() throws Exception {\n        suppress(methods(SuppressMethod.class, \"getObject\", \"getInt\"));\n\n        assertNull(new SuppressMethod().getObject());\n        assertEquals(0, new SuppressMethod().getInt());\n    }\n\n    @Test\n    public void suppressMultipleMethodsExample2() throws Exception {\n        suppress(methods(method(SuppressMethod.class, \"getObject\"), method(SuppressMethod.class, \"getInt\")));\n\n        assertNull(new SuppressMethod().getObject());\n        assertEquals(0, new SuppressMethod().getInt());\n    }\n\n    @Test\n    public void suppressAllMethodsExample() throws Exception {\n        suppress(methodsDeclaredIn(SuppressMethod.class));\n\n        final SuppressMethod tested = new SuppressMethod();\n\n        assertNull(tested.getObject());\n        assertNull(SuppressMethod.getObjectStatic());\n        assertEquals(0, tested.getByte());\n    }\n\n    @Test\n    public void suppressSingleFieldExample() throws Exception {\n        suppress(field(SuppressField.class, \"domainObject\"));\n\n        SuppressField tested = new SuppressField();\n        assertNull(tested.getDomainObject());\n    }\n\n    @Test\n    public void suppressConstructorExample() throws Exception {\n        suppress(constructor(SuppressConstructorHierarchy.class));\n\n        SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy(\"message\");\n\n        assertEquals(42, tested.getNumber());\n        assertNull(tested.getMessage());\n    }\n\n    @Test\n    public void stubSingleMethodExample() throws Exception {\n        final String expectedReturnValue = \"new\";\n        stub(method(SuppressMethod.class, \"getObject\")).toReturn(expectedReturnValue);\n\n        final SuppressMethod tested = new SuppressMethod();\n        assertEquals(expectedReturnValue, tested.getObject());\n        assertEquals(expectedReturnValue, tested.getObject());\n    }\n\n    @Test\n    public void duckTypeStaticMethodExample() throws Exception {\n        replace(method(SuppressMethod.class, \"getObjectStatic\")).with(\n                method(StaticAndInstanceDemo.class, \"getStaticMessage\"));\n\n        assertEquals(SuppressMethod.getObjectStatic(), StaticAndInstanceDemo.getStaticMessage());\n    }\n\n    @Test\n    public void whenReplacingMethodWithAMethodOfIncorrectReturnTypeThenAnIAEIsThrown() throws Exception {\n        try {\n            replace(method(SuppressMethod.class, \"getObjectStatic\")).with(\n                    method(StaticAndInstanceDemo.class, \"aVoidMethod\"));\n            fail(\"Should thow IAE\");\n        } catch (Exception e) {\n            assertEquals(\"The replacing method (public static void samples.staticandinstance.StaticAndInstanceDemo.aVoidMethod()) needs to return java.lang.Object and not void.\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void whenReplacingMethodWithAMethodOfWithIncorrectParametersThenAnIAEIsThrown() throws Exception {\n        try {\n            replace(method(SuppressMethod.class, \"getObjectStatic\")).with(\n                    method(StaticAndInstanceDemo.class, \"aMethod2\"));\n            fail(\"Should thow IAE\");\n        } catch (Exception e) {\n            assertEquals(\"The replacing method, \\\"public static java.lang.Object samples.staticandinstance.StaticAndInstanceDemo.aMethod2(java.lang.String)\\\", needs to have the same number of parameters of the same type as as method \\\"public static java.lang.Object samples.suppressmethod.SuppressMethod.getObjectStatic()\\\".\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void changingReturnValueExample() throws Exception {\n        replace(method(SuppressMethod.class, \"getObjectWithArgument\")).with(new ReturnValueChangingInvocationHandler());\n\n        final SuppressMethod tested = new SuppressMethod();\n\n        assertThat(tested.getObjectWithArgument(\"don't do anything\"), is(instanceOf(Object.class)));\n        assertEquals(\"hello world\", tested.getObjectWithArgument(\"make it a string\"));\n    }\n\n    @Test\n    public void suppressAllConstructors() throws Exception {\n        suppress(constructorsDeclaredIn(SuppressEverything.class));\n\n        SuppressEverything suppressEverything = new SuppressEverything();\n        new SuppressEverything(\"test\");\n\n        try {\n            suppressEverything.something();\n            fail(\"Should throw ISE\");\n        } catch (IllegalStateException e) {\n            assertEquals(\"error\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void suppressEverythingExample() throws Exception {\n        suppress(everythingDeclaredIn(SuppressEverything.class));\n\n        SuppressEverything suppressEverything = new SuppressEverything();\n        new SuppressEverything(\"test\");\n        suppressEverything.something();\n        suppressEverything.somethingElse();\n    }\n\n    private final class ReturnValueChangingInvocationHandler implements InvocationHandler {\n        @Override\n        public Object invoke(Object object, Method method, Object[] arguments) throws Throwable {\n            if (arguments[0].equals(\"make it a string\")) {\n                return \"hello world\";\n            } else {\n                return method.invoke(object, arguments);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalNonStaticMethodsTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.finalmocking.FinalDemo;\nimport samples.powermockito.junit4.finalmocking.MockFinalMethodsCases;\nimport samples.privateandfinal.PrivateFinal;\n\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito.\n */\n@PrepareForTest( { FinalDemo.class, PrivateFinal.class })\npublic class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases{\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalUsingAnnotationsTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.Mockito.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito and PowerMock\n * annotations.\n */\n@PrepareForTest(FinalDemo.class)\n@Ignore\npublic class MockFinalUsingAnnotationsTest {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    @Mock\n    private FinalDemo usingMockitoMockAnnotation;\n\n    @SuppressWarnings(\"deprecation\")\n    @org.mockito.Mock\n    private FinalDemo usingDeprecatedMockitoMockAnnotation;\n\n    @Test\n    public void assertMockFinalWithMockitoMockAnnotationWorks() throws Exception {\n        final String argument = \"hello\";\n\n        assertNull(usingMockitoMockAnnotation.say(argument));\n\n        verify(usingMockitoMockAnnotation).say(argument);\n    }\n\n    @Test\n    public void assertMockFinalWithDeprecatedMockitoMockAnnotationWorks() throws Exception {\n        final String argument = \"hello\";\n\n        assertNull(usingDeprecatedMockitoMockAnnotation.say(argument));\n\n        verify(usingDeprecatedMockitoMockAnnotation).say(argument);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.powermockito.junit4.staticmocking.MockStaticCases;\nimport samples.singleton.SimpleStaticService;\nimport samples.singleton.StaticService;\n\n/**\n * Test class to demonstrate static mocking with PowerMockito.\n */\n@PrepareForTest({StaticService.class, SimpleStaticService.class})\npublic class MockStaticTest extends MockStaticCases {\n    \n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n    \n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticWithPrivateCtorTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.singleton.StaticWithPrivateCtor;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n@PrepareForTest(StaticWithPrivateCtor.class)\npublic class MockStaticWithPrivateCtorTest {\n\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    @Test\n    public void canMockStaticMethodsInClassWithPrivateConstructor() throws Exception {\n        mockStatic(StaticWithPrivateCtor.class);\n        when(StaticWithPrivateCtor.staticMethod()).thenReturn(\"something else\");\n\n        assertEquals(\"something else\", StaticWithPrivateCtor.staticMethod());\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/PrivateInstanceMockingTest.java",
    "content": "package samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.powermockito.junit4.privatemocking.PrivateInstanceMockingCases;\nimport samples.privatemocking.PrivateMethodDemo;\n\n@PrepareForTest( { PrivateMethodDemo.class })\npublic class PrivateInstanceMockingTest extends PrivateInstanceMockingCases {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/StubMethodTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport org.powermock.reflect.exceptions.MethodNotFoundException;\nimport org.powermock.reflect.exceptions.TooManyMethodsFoundException;\nimport samples.suppressmethod.SuppressMethod;\n\nimport static junit.framework.Assert.fail;\nimport static org.junit.Assert.assertEquals;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.stub;\n\n@PrepareForTest(SuppressMethod.class)\npublic class StubMethodTest {\n\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expectedValue = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObject\")).toReturn(expectedValue);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\tassertEquals(expectedValue, tested.getObject());\n\t\tassertEquals(expectedValue, tested.getObject());\n\t}\n\n\t@Test\n\tpublic void whenStubbingStaticMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expectedValue = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObjectStatic\")).toReturn(expectedValue);\n\n\t\tassertEquals(expectedValue, SuppressMethod.getObjectStatic());\n\t\tassertEquals(expectedValue, SuppressMethod.getObjectStatic());\n\t}\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodWithPrimiteValueTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tfloat expectedValue = 4;\n\t\tstub(method(SuppressMethod.class, \"getFloat\")).toReturn(expectedValue);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\tassertEquals(expectedValue, tested.getFloat(), 0.0f);\n\t\tassertEquals(expectedValue, tested.getFloat(), 0.0f);\n\t}\n\n\t@Test(expected = TooManyMethodsFoundException.class)\n\tpublic void whenSeveralMethodsFoundThenTooManyMethodsFoundExceptionIsThrown() throws Exception {\n\t\tstub(method(SuppressMethod.class, \"sameName\"));\n\t}\n\n\t@Test(expected = MethodNotFoundException.class)\n\tpublic void whenNoMethodsFoundThenMethodNotFoundExceptionIsThrown() throws Exception {\n\t\tstub(method(SuppressMethod.class, \"notFound\"));\n\t}\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expected = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObject\")).toReturn(expected);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\tassertEquals(expected, tested.getObject());\n\t\tassertEquals(expected, tested.getObject());\n\t}\n\n\t@Test\n\tpublic void whenStubbingStaticMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception {\n\t\tString expected = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getObjectStatic\")).toReturn(expected);\n\n\t\tassertEquals(expected, SuppressMethod.getObjectStatic());\n\t\tassertEquals(expected, SuppressMethod.getObjectStatic());\n\t}\n\n\t@Test(expected = ClassCastException.class)\n\tpublic void whenStubbingInstanceMethodWithWrongReturnTypeThenClasscastExceptionIsThrown() throws Exception {\n\t\tString illegalReturnType = \"Hello\";\n\t\tstub(method(SuppressMethod.class, \"getFloat\")).toReturn(illegalReturnType);\n\t\tSuppressMethod tested = new SuppressMethod();\n\t\ttested.getFloat();\n\t}\n\n\t@Test\n\tpublic void whenStubbingInstanceMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception {\n\t\tException expected = new Exception(\"message\");\n\t\tstub(method(SuppressMethod.class, \"getObject\")).toThrow(expected);\n\n\t\tSuppressMethod tested = new SuppressMethod();\n\n\t\ttry {\n\t\t\ttested.getObject();\n\t\t\tfail();\n\t\t} catch (Exception e) {\n\t\t\tassertEquals(\"message\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void whenStubbingStaticMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception {\n\t\tException expected = new Exception(\"message\");\n\t\tstub(method(SuppressMethod.class, \"getObjectStatic\")).toThrow(expected);\n\t\ttry {\n\t\t\tSuppressMethod.getObjectStatic();\n\t\t\tfail();\n\t\t} catch (Exception e) {\n\t\t\tassertEquals(\"message\", e.getMessage());\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorDemoTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.suppressconstructor.SuppressConstructorDemo;\nimport samples.suppressconstructor.SuppressConstructorSubclassDemo;\n\nimport static org.junit.Assert.assertNull;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n/**\n * This test demonstrates how to tell PowerMock to avoid executing constructor\n * code for a certain class. This is crucial in certain tests where the\n * constructor or a subclass's constructor performs operations that are of no\n * concern to the unit test of the actual class or if the constructor performs\n * operations, such as getting services from a runtime environment that has not\n * been initialized. In normal situations you're forced to create an integration\n * or function test for the class instead (and thus the runtime environment is\n * available). This is not particularly good when it comes to testing method\n * logic.\n */\n@PrepareForTest(SuppressConstructorDemo.class)\npublic class SuppressConstructorDemoTest {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    /**\n     * This test makes sure that the real constructor has never been called.\n     */\n    @Test\n    public void testSuppressConstructor() throws Exception {\n        suppress(constructor(SuppressConstructorDemo.class));\n        final SuppressConstructorDemo tested = new SuppressConstructorDemo(\"a message\");\n        assertNull(\"Message should have been null since we're skipping the execution of the constructor code.\", tested.getMessage());\n    }\n\n    /**\n     * This test makes sure that the real parent constructor has never been\n     * called.\n     */\n    @Test\n    @Ignore(\"Doesn't work when using the Java agent\")\n    public void testSuppressParentConstructor() throws Exception {\n        suppress(constructor(SuppressConstructorSubclassDemo.class));\n        final SuppressConstructorDemo tested = new SuppressConstructorDemo(\"a message\");\n        assertNull(\"Message should have been null since we're skipping the execution of the constructor code.\", tested.getMessage());\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorHierarchyDemoTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.suppressconstructor.InvokeConstructor;\nimport samples.suppressconstructor.SuppressConstructorHierarchy;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@PrepareForTest(SuppressConstructorHierarchy.class)\npublic class SuppressConstructorHierarchyDemoTest {\n\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n\t@Test\n    @Ignore(\"Doesn't work from the java agent\")\n\tpublic void testSuppressConstructorHierarchy() throws Exception {\n\t\tsuppress(constructor(SuppressConstructorHierarchy.class));\n\t\tfinal String message = new InvokeConstructor().doStuff(\"qwe\");\n\t\tassertNull(\"Message should have been null since we're skipping the execution of the constructor code. Message was \\\"\" + message + \"\\\".\",\n\t\t\t\tmessage);\n\t}\n\n\t@Test\n\t@PrepareForTest\n\tpublic void testNotSuppressConstructorWithoutByteCodeManipulation() throws Exception {\n\t\ttry {\n\t\t\tnew SuppressConstructorHierarchy(\"message\");\n\t\t\tfail(\"Should throw RuntimeException since we're running this test with a new class loader!\");\n\t\t} catch (RuntimeException e) {\n\t\t\tassertEquals(\"This should be suppressed!!\", e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testNotSuppressConstructorWithByteCodeManipulation() throws Exception {\n\t\ttry {\n\t\t\tnew SuppressConstructorHierarchy(\"message\");\n\t\t\tfail(\"Should throw RuntimeException since we're running this test with a new class loader!\");\n\t\t} catch (RuntimeException e) {\n\t\t\tassertEquals(\"This should be suppressed!!\", e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * This simple test demonstrate that it's possible to continue execution\n\t * with the default {@code PrepareForTest} settings (i.e. using a\n\t * byte-code manipulated version of the SuppressConstructorHierarchyDemo\n\t * class).\n\t */\n\t@Test\n\tpublic void testSuppressConstructorHierarchyAgain() throws Exception {\n\t\tsuppress(constructor(SuppressConstructorHierarchy.class));\n\t\tSuppressConstructorHierarchy tested = new SuppressConstructorHierarchy(\"message\");\n\t\tassertEquals(42, tested.getNumber());\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.system.SystemClassUser;\n\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\nimport static org.mockito.Mockito.times;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n/**\n * Demonstrates PowerMockito's ability to mock non-final and final system\n * classes. To mock a system class you need to prepare the calling class for\n * testing. I.e. let's say you're testing class A which interacts with\n * URLEncoder then you would do:\n * \n * <pre>\n * \n * &#064;PrepareForTest({A.class})\n * \n * </pre>\n */\n@SuppressWarnings(\"MalformedFormatString\")\n@PrepareForTest( { SystemClassUser.class })\npublic class SystemClassUserTest {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n\n        when(URLEncoder.encode(\"string\", \"enc\")).thenReturn(\"something\");\n\n        assertEquals(\"something\", new SystemClassUser().performEncode());\n    }\n\n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n\n        Runtime runtimeMock = mock(Runtime.class);\n        Process processMock = mock(Process.class);\n\n        when(Runtime.getRuntime()).thenReturn(runtimeMock);\n        when(runtimeMock.exec(\"command\")).thenReturn(processMock);\n\n        assertSame(processMock, new SystemClassUser().executeCommand());\n    }\n\n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n\n        when(System.getProperty(\"property\")).thenReturn(\"my property\");\n\n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        spy(System.class);\n\n        doReturn(2L).when(System.class);\n        System.nanoTime();\n\n        new SystemClassUser().doMoreComplicatedStuff();\n\n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n    }\n\n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n\n        Collections.shuffle(list);\n\n        new SystemClassUser().shuffleCollection(list);\n\n        verifyStatic(Collections.class, times(2));\n        Collections.shuffle(list);\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        spy(System.class);\n\n        doReturn(\"my property\").when(System.class);\n        System.getProperty(\"property\");\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n\n        assertEquals(\"my property\", System.getProperty(\"to\"));\n    }\n\n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n\n        when(String.format(string, args)).thenReturn(returnValue);\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/WhenNewTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.agent;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\nimport samples.powermockito.junit4.whennew.WhenNewCases;\n\nimport java.io.DataInputStream;\n/**\n * Test class to demonstrate new instance mocking using whenConstructionOf(..).\n * \n */\n@SuppressWarnings(\"PrimitiveArrayArgumentToVariableArgMethod\")\n@PrepareForTest({ MyClass.class, ExpectNewDemo.class, DataInputStream.class })\npublic class WhenNewTest extends WhenNewCases {\n\t@Rule\n\tpublic PowerMockRule powerMockRule = new PowerMockRule();\n\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/Github512Test.java",
    "content": "package samples.powermockito.junit4.agent.github512;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PowerMockIgnore;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.singleton.StaticService;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.method;\nimport static org.powermock.api.mockito.PowerMockito.suppress;\n\n@PowerMockIgnore(\"org.assertj.*\")\npublic class Github512Test {\n\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n\n    @Test\n    @PrepareForTest(StaticService.class)\n    public void shouldSuppressMethodWithPrepareForTestOnMethod() {\n        suppress(method(StaticService.class, \"calculate\"));\n        assertThat(StaticService.calculate(1, 5)).isEqualTo(0);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/package-info.java",
    "content": "/**\n *  https://github.com/jayway/powermock/issues/512\n */\npackage samples.powermockito.junit4.agent.github512;"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/EnclosedTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport org.junit.Test;\nimport org.junit.experimental.runners.Enclosed;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport samples.staticandinstance.StaticAndInstanceDemo;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.junit.Assert.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n/**\n * Demonstrates how PowerMockRunner with annotation PowerMockRunnerDelegate can\n * provide PowerMock features to yet-another JUnit runner.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Enclosed.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class EnclosedTest {\n\n    private static final String stubbedReturnValue\n            = \"Stubbed return-value from \" + EnclosedTest.class;\n\n    public static class NoStubbing {\n\n        @Test\n        public void noStubbing() {\n            assertThat(\"Original return-value of #getStaticMessage()\",\n                    StaticAndInstanceDemo.getStaticMessage(),\n                    not(equalTo(stubbedReturnValue)));\n        }\n    }\n\n    public static class StubbedStaticReturnValue {\n\n        @Test\n        public void stubbedStaticReturnValue() {\n            mockStatic(StaticAndInstanceDemo.class);\n            when(StaticAndInstanceDemo.getStaticMessage())\n                    .thenReturn(stubbedReturnValue);\n            assertThat(\"Stubbed return-value of #getStaticMessag()\",\n                    StaticAndInstanceDemo.getStaticMessage(),\n                    equalTo(stubbedReturnValue));\n            verifyStatic(StaticAndInstanceDemo.class);\n            StaticAndInstanceDemo.getStaticMessage();\n            verifyNoMoreInteractions(StaticAndInstanceDemo.class);\n        }\n    }\n\n    public static class WhenStubbingIsOver {\n\n        @Test\n        public void whenStubbingIsOver() {\n            assertThat(\"Back to original return-value of #getStaticMessage()\",\n                    StaticAndInstanceDemo.getStaticMessage(),\n                    not(equalTo(stubbedReturnValue)));\n        }\n    }\n\n    public static class SubClass extends StubbedStaticReturnValue {}\n\n    public static class SubClassWithExtraNonPublicConstructors\n    extends StubbedStaticReturnValue {\n        public SubClassWithExtraNonPublicConstructors() {}\n        private SubClassWithExtraNonPublicConstructors(boolean arg) {}\n        protected SubClassWithExtraNonPublicConstructors(String arg) {}\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/JUnitParamsTest.java",
    "content": "package powermock.modules.test.mockito.junit4.delegate;\n\nimport junitparams.JUnitParamsRunner;\nimport junitparams.Parameters;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\n\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.Mockito.when;\n\n@PowerMockRunnerDelegate(JUnitParamsRunner.class)\n@PrepareForTest(Math.class)\n@RunWith(PowerMockRunner.class)\npublic class JUnitParamsTest {\n\n    @Before\n    public void setUp() {\n        PowerMockito.mockStatic(Math.class);\n        when(Math.addExact(anyInt(), anyInt())).thenReturn(42);\n    }\n\n    @Test\n    @Parameters({\"11, 234\", \"-54, 43\"})\n    public void testSum(int a, int b) {\n        Assert.assertEquals(42, Math.addExact(a, b));\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/MultipleConstructorsTest.java",
    "content": "/*\n * Copyright 2015 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\n\n/**\n * Verifies that an additional non-public constructor does not break the test-run.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate\npublic class MultipleConstructorsTest {\n\n    public MultipleConstructorsTest() {\n    }\n\n    protected MultipleConstructorsTest(String s) {\n    }\n\n    @Test\n    public void dummyTest() {}\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SelfieTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport org.hamcrest.Matcher;\nimport org.junit.runner.Description;\nimport org.junit.runner.RunWith;\nimport org.junit.runner.Runner;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunNotifier;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport samples.staticandinstance.StaticAndInstanceDemo;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.junit.runner.Description.createTestDescription;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n/**\n * Demonstrates how PowerMockRunner with annotation PowerMockRunnerDelegate can\n * provide a low-level JUnit (in this case a self-contained \"selfie\" test)\n * with some PowerMock abilities.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(SelfieTest.class)\n@PrepareForTest(StaticAndInstanceDemo.class)\npublic class SelfieTest extends Runner {\n\n    private static final String stubbedReturnValue\n            = \"Stubbed return-value from \" + SelfieTest.class;\n\n    private static final Description first = createTestDescription(\n            SelfieTest.class, \"No Stubbing\");\n    private static final Description second = createTestDescription(\n            SelfieTest.class, \"Stubbed Static Return-Value\");\n\n    /**\n     * Mandatory Runner constructor\n     */\n    public SelfieTest(Class<SelfieTest> ignore) {\n    }\n\n    @Override\n    public Description getDescription() {\n        Description desc = Description\n                .createSuiteDescription(SelfieTest.class);\n        desc.addChild(first);\n        desc.addChild(second);\n        return desc;\n    }\n\n    @Override\n    public void run(RunNotifier notifier) {\n        assert_getStaticMessage(notifier, first,\n                not(equalTo(stubbedReturnValue)));\n        mockStatic(StaticAndInstanceDemo.class);\n        when(StaticAndInstanceDemo.getStaticMessage())\n                .thenReturn(stubbedReturnValue);\n        assert_getStaticMessage(notifier, second, equalTo(stubbedReturnValue));\n    }\n\n    void assert_getStaticMessage(RunNotifier notifier, Description currentTest,\n            Matcher<? super String> getStaticMessageExpectation) {\n        notifier.fireTestStarted(currentTest);\n        try {\n            String staticMessage = StaticAndInstanceDemo.getStaticMessage();\n            if (getStaticMessageExpectation.matches(staticMessage)) {\n                notifier.fireTestFinished(currentTest);\n            } else {\n                notifier.fireTestFailure(new Failure(currentTest, new AssertionError(\n                        \"Unexpected #getStaticMessage() return-value: \"\n                        + staticMessage)));\n            }\n        } catch (Exception ex) {\n            notifier.fireTestFailure(new Failure(currentTest, ex));\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SubclassDelegateTest.java",
    "content": "/*\n * Copyright 2015 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\n\n/**\n * To verify that annotation {@link PowerMockRunnerDelegate} works OK when the\n * test-class has a super-class that will be loaded from the same class-loader.\n * (This used to make JUnit's default runner fail with\n * java.lang.IllegalArgumentException: Test class can only have one constructor\n * during initialization.)\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate\npublic class SubclassDelegateTest extends SuperClass {\n\n    @Test\n    public void test() {}\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuperClass.java",
    "content": "/*\n * Copyright 2015 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nclass SuperClass {}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethod.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport samples.suppressmethod.SuppressMethod;\n\npublic enum SuppressedMethod {\n\n    getObject {\n                @Override\n                public Object invokeOn(SuppressMethod tested) {\n                    return tested.getObject();\n                }\n            },\n    getObjectStatic {\n                @Override\n                public Object invokeOn(SuppressMethod tested) {\n                    return SuppressMethod.getObjectStatic();\n                }\n            },\n    getFloat {\n                @Override\n                public Object invokeOn(SuppressMethod tested) {\n                    return tested.getFloat();\n                }\n            };\n\n    public abstract Object invokeOn(SuppressMethod tested);\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethodStubbing.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport java.util.concurrent.Callable;\nimport org.powermock.api.support.membermodification.strategy.MethodStubStrategy;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\n\npublic enum SuppressedMethodStubbing {\n\n    Hello(\"Hello\"),\n    float_4(4.0F),\n    exception(new Exception(\"message\")) {\n                @Override\n                public <T> void enforceOn(MethodStubStrategy<T> stub) {\n                    stub.toThrow((Exception) value);\n                }\n\n                @Override\n                public void verify(final Callable<?> invocation) throws Exception {\n                    super.verify(new Callable<Exception>() {\n                        @Override\n                        public Exception call() {\n                            try {\n                                invocation.call();\n                                fail(\"Expected exception: \" + value);\n                                return null;\n                            } catch (Exception actualException) {\n                                return actualException;\n                            }\n                        }\n                    });\n                }\n\n                @Override\n                public String toString() {\n                    return \"throws Exception\";\n                }\n            };\n\n    final Object value;\n\n    private SuppressedMethodStubbing(Object value) {\n        this.value = value;\n    }\n\n    public <T> void enforceOn(MethodStubStrategy<T> stub) {\n        stub.toReturn((T) value);\n    }\n\n    public void verify(Callable<?> invocation) throws Exception {\n        assertEquals(value, invocation.call());\n    }\n\n    @Override\n    public String toString() {\n        return \"returns \" + value;\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserCases.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport samples.system.SystemClassUser;\n\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\nimport static org.mockito.Mockito.times;\nimport static org.powermock.api.mockito.PowerMockito.*;\n\n/**\n * Demonstrates PowerMockito's ability to mock non-final and final system\n * classes. To mock a system class you need to prepare the calling class for\n * testing. I.e. let's say you're testing class A which interacts with\n * URLEncoder then you would do:\n *\n * <pre>\n *\n * &#064;PrepareForTest({A.class})\n *\n * </pre>\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest({SystemClassUser.class})\npublic class SystemClassUserCases {\n\n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n\n        when(URLEncoder.encode(\"string\", \"enc\")).thenReturn(\"something\");\n\n        assertEquals(\"something\", new SystemClassUser().performEncode());\n    }\n\n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n\n        Runtime runtimeMock = mock(Runtime.class);\n        Process processMock = mock(Process.class);\n\n        when(Runtime.getRuntime()).thenReturn(runtimeMock);\n        when(runtimeMock.exec(\"command\")).thenReturn(processMock);\n\n        assertSame(processMock, new SystemClassUser().executeCommand());\n    }\n\n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n\n        when(System.getProperty(\"property\")).thenReturn(\"my property\");\n\n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        spy(System.class);\n\n        doReturn(2L).when(System.class);\n        System.nanoTime();\n\n        new SystemClassUser().doMoreComplicatedStuff();\n\n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n    }\n\n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n\n        Collections.shuffle(list);\n\n        new SystemClassUser().shuffleCollection(list);\n\n        verifyStatic(Collections.class, times(2));\n        Collections.shuffle(list);\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        spy(System.class);\n\n        doReturn(\"my property\").when(System.class);\n        System.getProperty(\"property\");\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n\n        assertEquals(\"my property\", System.getProperty(\"to\"));\n    }\n\n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n\n        when(String.format(string, args)).thenReturn(returnValue);\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserMethod.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Test;\n\npublic class SystemClassUserMethod {\n\n    private final Method method;\n\n    public SystemClassUserMethod(Method method) {\n        this.method = method;\n    }\n\n    public static SystemClassUserMethod[] values() {\n        Method[] methods = SystemClassUserCases.class.getDeclaredMethods();\n        List<SystemClassUserMethod> values =\n                new ArrayList<SystemClassUserMethod>(methods.length);\n        for (Method m : methods) {\n            if (m.isAnnotationPresent(Test.class)) {\n                values.add(new SystemClassUserMethod(m));\n            }\n        }\n        return values.toArray(new SystemClassUserMethod[values.size()]);\n    }\n\n    @Override\n    public String toString() {\n        return method.getName();\n    }\n\n    public Method getMethod() {\n        return method;\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCaseMethod.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Test;\nimport samples.powermockito.junit4.whennew.WhenNewCases;\n\npublic class WhenNewCaseMethod {\n\n    final Method testMethod;\n\n    public WhenNewCaseMethod(Method testMethod) {\n        this.testMethod = testMethod;\n    }\n\n    @Override\n    public String toString() {\n        return testMethod.getName();\n    }\n\n    public void runTest() throws Throwable {\n        try {\n            testMethod.invoke(new WhenNewCases());\n        } catch (InvocationTargetException ex) {\n            throw ex.getTargetException();\n        }\n    }\n\n    public boolean nullPointerIsExpected() {\n        return NullPointerException.class\n                == testMethod.getAnnotation(Test.class).expected();\n    }\n\n    public static WhenNewCaseMethod[] values() {\n        Method[] methods = WhenNewCases.class.getDeclaredMethods();\n        List<WhenNewCaseMethod> values\n                = new ArrayList<WhenNewCaseMethod>(methods.length);\n        for (Method m : methods) {\n            if (m.isAnnotationPresent(Test.class)) {\n                values.add(new WhenNewCaseMethod(m));\n            }\n        }\n        return values.toArray(new WhenNewCaseMethod[values.size()]);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/FinalDemoTest.java",
    "content": "/*\n * Copyright 2011-2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\n\nimport java.lang.reflect.Method;\nimport java.util.Collection;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport samples.finalmocking.FinalDemo;\nimport samples.privateandfinal.PrivateFinal;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.powermock.api.mockito.PowerMockito.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\n@PrepareForTest({FinalDemo.class, PrivateFinal.class})\npublic class FinalDemoTest {\n\n    @Parameterized.Parameter(0)\n    public String expected;\n\n    @Parameterized.Parameters(name = \"expected={0}\")\n    public static Collection<?> expections() {\n        return java.util.Arrays.asList(new Object[][]{\n            {\"Hello altered World\"}, {\"something\"}, {\"test\"}\n        });\n    }\n\n    @Test\n    public void assertMockFinalWithNoExpectationsWorks() throws Exception {\n        final String argument = \"hello\";\n\n        FinalDemo tested = mock(FinalDemo.class);\n\n        assertNull(tested.say(argument));\n\n        verify(tested).say(argument);\n    }\n\n    @Test\n    public void assertMockFinalWithExpectationsWorks() throws Exception {\n        final String argument = \"hello\";\n\n        FinalDemo tested = mock(FinalDemo.class);\n\n        when(tested.say(argument)).thenReturn(expected);\n\n        final String actual = \"\" + tested.say(argument);\n\n        verify(tested).say(argument);\n\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void assertFinalNativeWithExpectationsWorks() throws Exception {\n        final String argument = \"hello\";\n\n        FinalDemo tested = mock(FinalDemo.class);\n\n        when(tested.sayFinalNative(argument)).thenReturn(expected);\n\n        String actual = \"\" + tested.sayFinalNative(argument);\n\n        verify(tested).sayFinalNative(argument);\n        assertEquals(\"Expected and actual did not match\", expected, actual);\n    }\n\n    @Test\n    public void assertSpyingOnFinalInstanceMethodWorks() throws Exception {\n        FinalDemo tested = new FinalDemo();\n        FinalDemo spy = spy(tested);\n\n        final String argument = \"PowerMock\";\n\n        assertEquals(\"Hello \" + argument, spy.say(argument));\n        when(spy.say(argument)).thenReturn(expected);\n        assertEquals(expected, \"\" + spy.say(argument));\n    }\n\n    @Test(expected = ArrayStoreException.class)\n    public void assertSpyingOnFinalVoidInstanceMethodWorks() throws Exception {\n        FinalDemo tested = new FinalDemo();\n        FinalDemo spy = spy(tested);\n\n        doThrow(new ArrayStoreException()).when(spy).finalVoidCallee();\n\n        spy.finalVoidCaller();\n    }\n\n    @Test\n    public void assertSpyingOnPrivateFinalInstanceMethodWorks() throws Exception {\n        PrivateFinal spy = spy(new PrivateFinal());\n\n        assertEquals(\"Hello \" + expected, spy.say(expected));\n\n        when(spy, \"sayIt\", isA(String.class)).thenReturn(expected);\n\n        assertEquals(expected, \"\" + spy.say(expected));\n\n        verifyPrivate(spy, times(2)).invoke(\"sayIt\", expected);\n    }\n\n    @Test\n    public void assertSpyingOnPrivateFinalInstanceMethodWorksWhenUsingJavaLangReflectMethod() throws Exception {\n        PrivateFinal spy = spy(new PrivateFinal());\n\n        assertEquals(\"Hello \" + expected, spy.say(expected));\n\n        final Method methodToExpect = method(PrivateFinal.class, \"sayIt\");\n        when(spy, methodToExpect).withArguments(isA(String.class)).thenReturn(expected);\n\n        assertEquals(expected, \"\" + spy.say(expected));\n\n        verifyPrivate(spy, times(2)).invoke(methodToExpect).withArguments(expected);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/MockFinalUsingAnnotationsTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.mockito.Mock;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport org.powermock.reflect.Whitebox;\nimport samples.finalmocking.FinalDemo;\n\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.Mockito.verify;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito and PowerMock\n * annotations.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\n@PrepareForTest(FinalDemo.class)\npublic class MockFinalUsingAnnotationsTest {\n\n    @Mock\n    private FinalDemo usingMockitoMockAnnotation;\n\n    @org.mockito.Mock\n    private FinalDemo usingDeprecatedMockitoMockAnnotation;\n\n    @Parameterized.Parameter(0)\n    public MockField field2test;\n\n    @Test\n    public void testMockFinal() throws Exception {\n        final String argument = \"hello\";\n        System.out.println(field2test);\n        FinalDemo mockedFinal = field2test.inTest(this);\n        assertNull(mockedFinal.say(argument));\n        verify(mockedFinal).say(argument);\n    }\n\n    @Parameterized.Parameters(name = \"{0}\")\n    public static List<?> vals() {\n        MockField[] mockFields = MockField.values();\n        List<Object[]> vals = new ArrayList<Object[]>(mockFields.length);\n        for (MockField each : mockFields) {\n            vals.add(new Object[]{each});\n        }\n        return vals;\n    }\n\n    enum MockField {\n\n        usingMockitoMockAnnotation,\n        usingDeprecatedMockitoMockAnnotation;\n\n        <T> T inTest(Object test) {\n            try {\n                return (T) Whitebox.getInternalState(test, name());\n            } catch (Exception ex) {\n                throw new Error(ex);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/StubMethodTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.Callable;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport powermock.modules.test.mockito.junit4.delegate.SuppressedMethod;\nimport powermock.modules.test.mockito.junit4.delegate.SuppressedMethodStubbing;\nimport samples.suppressmethod.SuppressMethod;\n\nimport static org.powermock.api.support.membermodification.MemberMatcher.method;\nimport static org.powermock.api.support.membermodification.MemberModifier.stub;\nimport static powermock.modules.test.mockito.junit4.delegate.SuppressedMethod.*;\nimport static powermock.modules.test.mockito.junit4.delegate.SuppressedMethodStubbing.*;\n\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\n@PrepareForTest(SuppressMethod.class)\npublic class StubMethodTest {\n\n    @Parameterized.Parameter(0)\n    public SuppressedMethod method;\n\n    @Parameterized.Parameter(1)\n    public SuppressedMethodStubbing stubbing;\n\n    @Test\n    public void test() throws Exception {\n        stubbing.enforceOn(stub(method(SuppressMethod.class, method.name())));\n\n        final SuppressMethod tested = new SuppressMethod();\n        Callable<?> methodInvocation = new Callable<Object>() {\n            @Override\n            public Object call() {\n                return method.invokeOn(tested);\n            }\n        };\n\n        stubbing.verify(methodInvocation);\n        stubbing.verify(methodInvocation);\n        stubbing.verify(methodInvocation);\n    }\n\n    @Parameterized.Parameters(name = \" {0} {1}\")\n    public static List<?> paramValues() {\n        return Arrays.asList(new Object[][]{\n            {getObject, Hello},\n            {getObject, float_4},\n            {getObject, exception},\n            {getObjectStatic, Hello},\n            {getObjectStatic, float_4},\n            {getObjectStatic, exception},\n            //\t\t\t{getFloat, Hello},  //Incompatible return-type\n            {getFloat, float_4},\n            {getFloat, exception},});\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorDemoTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport samples.suppressconstructor.SuppressConstructorDemo;\nimport samples.suppressconstructor.SuppressConstructorSubclassDemo;\n\nimport static org.junit.Assert.assertNull;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n/**\n * This test demonstrates how to tell PowerMock to avoid executing constructor\n * code for a certain class. This is crucial in certain tests where the\n * constructor or a subclass's constructor performs operations that are of no\n * concern to the unit test of the actual class or if the constructor performs\n * operations, such as getting services from a runtime environment that has not\n * been initialized. In normal situations you're forced to create an integration\n * or function test for the class instead (and thus the runtime environment is\n * available). This is not particularly good when it comes to testing method\n * logic.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\n@PrepareForTest(SuppressConstructorDemo.class)\npublic class SuppressConstructorDemoTest {\n\n    final Class<? super SuppressConstructorDemo> constructor2suppress;\n\n    public SuppressConstructorDemoTest(\n            Class<? super SuppressConstructorDemo> constructor2suppress) {\n        this.constructor2suppress = constructor2suppress;\n    }\n\n    /**\n     * This test makes sure that the real constructor has never been called.\n     */\n    @Test\n    public void testSuppressConstructor() throws Exception {\n        suppress(constructor(constructor2suppress));\n        final SuppressConstructorDemo tested = new SuppressConstructorDemo(\"a message\");\n        assertNull(\"Message should have been null since we're skipping the execution of the constructor code.\", tested.getMessage());\n    }\n\n    @Parameterized.Parameters(name = \"{0}\")\n    public static List<?> classesWithConstructor2suppress() {\n        List<?> constructorClasses = Arrays.asList(new Object[][]{\n            {SuppressConstructorSubclassDemo.class},\n            {SuppressConstructorDemo.class}\n        });\n        Collections.shuffle(constructorClasses);\n        return constructorClasses;\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorHierarchyDemoTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport samples.suppressconstructor.InvokeConstructor;\nimport samples.suppressconstructor.SuppressConstructorHierarchy;\n\nimport static org.junit.Assert.*;\nimport static org.powermock.api.support.membermodification.MemberMatcher.constructor;\nimport static org.powermock.api.support.membermodification.MemberModifier.suppress;\n\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\n@PrepareForTest(SuppressConstructorHierarchy.class)\npublic class SuppressConstructorHierarchyDemoTest {\n\n    @Parameterized.Parameter\n    public boolean suppress;\n\n    @Parameterized.Parameters(name = \"suppress={0}\")\n    public static List<?> false_or_true() {\n        return Arrays.asList(new Object[][]{{false}, {true}});\n    }\n\n    @Before\n    public void suppressOnDemand() {\n        if (suppress) {\n            suppress(constructor(SuppressConstructorHierarchy.class));\n        }\n    }\n\n    @Test\n    public void directConstructorUsage() throws Exception {\n        System.out.println(\"ClassLoader: \" + getClass().getClassLoader());\n        try {\n            SuppressConstructorHierarchy tested\n                    = new SuppressConstructorHierarchy(\"message\");\n            if (suppress) {\n                assertNull(\n                        \"Message should have been null since we're skipping the execution of the constructor code. Message was \\\"message\\\".\",\n                        tested.getMessage());\n                assertEquals(\"getNumber() value\", 42, tested.getNumber());\n            } else {\n                fail(\"Expected RuntimeException\");\n            }\n        } catch (RuntimeException ex) {\n            if (suppress) {\n                throw ex;\n            } else {\n                assertEquals(\"This should be suppressed!!\", ex.getMessage());\n            }\n        }\n    }\n\n    @Test\n    public void useConstructorInvoker() throws Exception {\n        System.out.println(\"ClassLoader: \" + getClass().getClassLoader());\n        try {\n            final String message = new InvokeConstructor().doStuff(\"qwe\");\n            if (suppress) {\n                assertNull(\"Message should have been null since we're skipping the execution of the constructor code. Message was \\\"\" + message + \"\\\".\",\n                        message);\n            } else {\n                fail(\"Expected RuntimeException\");\n            }\n        } catch (RuntimeException ex) {\n            if (suppress) {\n                throw ex;\n            } else {\n                assertEquals(\"This should be suppressed!!\", ex.getMessage());\n            }\n        }\n    }\n\n    @Test\n    @PrepareForTest\n    public void suppressWithoutByteCodeManipulation() throws Exception {\n        System.out.println(\"ClassLoader: \" + getClass().getClassLoader());\n        try {\n            new InvokeConstructor().doStuff(\"qwe\");\n            fail(\"Should throw RuntimeException since we're running this test with a new class loader!\");\n        } catch (RuntimeException ex) {\n            assertEquals(\"This should be suppressed!!\", ex.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SupressMethodExampleTest.java",
    "content": "/*\n * Copyright 2011-2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.hamcrest.Matcher;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport samples.suppressconstructor.SuppressConstructorHierarchy;\nimport samples.suppresseverything.SuppressEverything;\nimport samples.suppressfield.SuppressField;\nimport samples.suppressmethod.SuppressMethod;\nimport samples.suppressfield.DomainObject;\n\nimport static org.hamcrest.CoreMatchers.instanceOf;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.nullValue;\nimport static org.junit.Assert.*;\nimport static org.powermock.api.support.membermodification.MemberModifier.*;\n\n/**\n * Demonstrates PowerMock's ability to modify member structures.\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\n@PrepareForTest({SuppressMethod.class, SuppressField.class, SuppressEverything.class})\npublic class SupressMethodExampleTest {\n\n    enum GetObjectSuppression {\n\n        DONT_SUPPRESS(SuppressMethod.OBJECT),\n        SUPPRESS(null) {\n                    @Override\n                    void doIt() {\n                        suppress(method(SuppressMethod.class, \"getObject\"));\n                    }\n                };\n\n        final Object expectedReturnValue;\n\n        GetObjectSuppression(Object expectedReturnValue) {\n            this.expectedReturnValue = expectedReturnValue;\n        }\n\n        void doIt() {\n        }\n    }\n\n    enum GetIntSuppression {\n\n        DONT_SUPPRESS(Integer.MAX_VALUE),\n        SUPPRESS(0) {\n                    @Override\n                    void doIt() {\n                        suppress(method(SuppressMethod.class, \"getInt\"));\n                    }\n                };\n\n        final int expectedReturnValue;\n\n        GetIntSuppression(int expectedReturnValue) {\n            this.expectedReturnValue = expectedReturnValue;\n        }\n\n        void doIt() {\n        }\n    }\n\n    enum FieldSuppression {\n\n        DONT_SUPPRESS(instanceOf(DomainObject.class)),\n        SUPPRESS(nullValue()) {\n                    @Override\n                    void doIt() {\n                        suppress(field(SuppressField.class, \"domainObject\"));\n                    }\n                };\n\n        final Matcher<? super DomainObject> expectation;\n\n        private FieldSuppression(Matcher<? super DomainObject> expectation) {\n            this.expectation = expectation;\n        }\n\n        void doIt() {\n        }\n    }\n\n    final GetObjectSuppression getObjectSuppression;\n    final GetIntSuppression getIntSuppression;\n    final FieldSuppression fieldSuppression;\n    final boolean suppressConstructor;\n\n    @Rule\n    public final ExpectedException expectedException = ExpectedException.none();\n\n    public SupressMethodExampleTest(\n            GetObjectSuppression getObjectSuppression,\n            GetIntSuppression getIntSuppression,\n            FieldSuppression fieldSuppression,\n            Boolean suppressConstructor) {\n        this.getObjectSuppression = getObjectSuppression;\n        this.getIntSuppression = getIntSuppression;\n        this.fieldSuppression = fieldSuppression;\n        this.suppressConstructor = suppressConstructor;\n    }\n\n    @Parameterized.Parameters(name = \"getObject={0}  getInt={1}  field={2}  suppressConstructor={3}\")\n    public static Collection<?> suppressionParamValues() {\n        return Arrays.asList(new Object[][]{\n            {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.DONT_SUPPRESS,\n                FieldSuppression.DONT_SUPPRESS, false},\n            {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.SUPPRESS,\n                FieldSuppression.DONT_SUPPRESS, false},\n            {GetObjectSuppression.SUPPRESS, GetIntSuppression.DONT_SUPPRESS,\n                FieldSuppression.DONT_SUPPRESS, true},\n            {GetObjectSuppression.SUPPRESS, GetIntSuppression.SUPPRESS,\n                FieldSuppression.DONT_SUPPRESS, true},\n            {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.DONT_SUPPRESS,\n                FieldSuppression.SUPPRESS, true},\n            {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.SUPPRESS,\n                FieldSuppression.SUPPRESS, true},\n            {GetObjectSuppression.SUPPRESS, GetIntSuppression.DONT_SUPPRESS,\n                FieldSuppression.SUPPRESS, false},\n            {GetObjectSuppression.SUPPRESS, GetIntSuppression.SUPPRESS,\n                FieldSuppression.SUPPRESS, false},});\n    }\n\n    @Test\n    public void verifySuppression() throws Exception {\n        getObjectSuppression.doIt();\n        getIntSuppression.doIt();\n        fieldSuppression.doIt();\n\n        assertEquals(\"getObject return-value\",\n                getObjectSuppression.expectedReturnValue,\n                new SuppressMethod().getObject());\n        assertEquals(\"getInt return-value\",\n                getIntSuppression.expectedReturnValue,\n                new SuppressMethod().getInt());\n        assertThat(\"Value from field\",\n                new SuppressField().getDomainObject(),\n                is(fieldSuppression.expectation));\n\n        if (suppressConstructor) {\n            suppress(constructor(SuppressConstructorHierarchy.class));\n        } else {\n            expectedException.expect(RuntimeException.class);\n        }\n        SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy(\"message\");\n        assertTrue(\"Or a runtime exception should have been thrown by now\", suppressConstructor);\n\n        assertEquals(42, tested.getNumber());\n        assertNull(tested.getMessage());\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.model.Statement;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport powermock.modules.test.mockito.junit4.delegate.SystemClassUserCases;\nimport powermock.modules.test.mockito.junit4.delegate.SystemClassUserMethod;\nimport samples.system.SystemClassUser;\n\n/**\n * Demonstrates PowerMockito's ability to mock non-final and final system\n * classes. To mock a system class you need to prepare the calling class for\n * testing. I.e. let's say you're testing class A which interacts with\n * URLEncoder then you would do:\n *\n * <pre>\n *\n * &#064;PrepareForTest({A.class})\n *\n * </pre>\n */\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\n@PrepareForTest({SystemClassUserCases.class, SystemClassUser.class})\npublic class SystemClassUserTest {\n\n    final Statement test;\n\n    public SystemClassUserTest(final SystemClassUserMethod testCase) {\n        test = new Statement() {\n            @Override\n            public void evaluate() throws Throwable {\n                try {\n                    testCase.getMethod().invoke(new SystemClassUserCases());\n                } catch (InvocationTargetException ex) {\n                    throw ex.getTargetException();\n                }\n            }\n        };\n    }\n\n    @Parameterized.Parameters(name = \"{0}\")\n    public static List<?> paramValues() {\n        List<Object[]> values = new ArrayList<Object[]>();\n        for (SystemClassUserMethod tstCase : SystemClassUserMethod.values()) {\n            values.add(new Object[]{tstCase});\n        }\n        return values;\n    }\n\n    @Test\n    public void __() throws Throwable {\n        test.evaluate();\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/WhenNewTest.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage powermock.modules.test.mockito.junit4.delegate.parameterized;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport samples.classwithinnermembers.ClassWithInnerMembers;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\n\nimport java.io.DataInputStream;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.powermock.modules.junit4.PowerMockRunner;\nimport org.powermock.modules.junit4.PowerMockRunnerDelegate;\nimport powermock.modules.test.mockito.junit4.delegate.WhenNewCaseMethod;\nimport samples.powermockito.junit4.whennew.WhenNewCases;\n\n@PrepareForTest({MyClass.class, ExpectNewDemo.class, ClassWithInnerMembers.class, DataInputStream.class,\n        WhenNewCases.class})\n@RunWith(PowerMockRunner.class)\n@PowerMockRunnerDelegate(Parameterized.class)\npublic class WhenNewTest {\n\n    @Rule\n    public final ExpectedException ee = ExpectedException.none();\n\n    @Parameterized.Parameter(0)\n    public WhenNewCaseMethod whenNewCase;\n\n    @Test\n    public void test() throws Throwable {\n        if (whenNewCase.nullPointerIsExpected()) {\n            ee.expect(NullPointerException.class);\n        }\n        whenNewCase.runTest();\n    }\n\n    @Parameterized.Parameters(name = \"{0}\")\n    public static Collection<Object[]> whenNewCases() {\n        WhenNewCaseMethod[] cases = WhenNewCaseMethod.values();\n        List<Object[]> paramValues = new ArrayList<Object[]>(cases.length);\n        for (WhenNewCaseMethod each : cases) {\n            paramValues.add(new Object[]{each});\n        }\n        return paramValues;\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/Foo.java",
    "content": "package samples.powermockito.junit4.rule.objenesis;\n\npublic class Foo {\n\n\tpublic Bar m() {\n\t\treturn new Bar(1);\n\t}\n\n\t@SuppressWarnings(\"SameParameterValue\")\n\tpublic static class Bar {\n\n\t\tprivate final int i;\n\n\t\tBar(final int i) {\n\t\t\tthis.i = i;\n\t\t}\n\n\t\tpublic int getI() {\n\t\t\treturn i;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockFinalNonStaticMethodsTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.objenesis;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.finalmocking.FinalDemo;\nimport samples.powermockito.junit4.finalmocking.MockFinalMethodsCases;\nimport samples.privateandfinal.PrivateFinal;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito.\n */\n@PrepareForTest( { FinalDemo.class, PrivateFinal.class })\npublic class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.objenesis;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.powermockito.junit4.staticmocking.MockStaticCases;\nimport samples.singleton.SimpleStaticService;\nimport samples.singleton.StaticService;\n\n/**\n * Test class to demonstrate static mocking with PowerMockito.\n */\n@PrepareForTest({StaticService.class, SimpleStaticService.class})\npublic class MockStaticTest extends MockStaticCases {\n    \n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n    \n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PowerMockRuleTest.java",
    "content": "package samples.powermockito.junit4.rule.objenesis;\n\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.classloader.annotations.PowerMockIgnore;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport org.powermock.reflect.Whitebox;\nimport samples.powermockito.junit4.rule.objenesis.Foo.Bar;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\n\n@PowerMockIgnore({\"org.mockito.*\",\"org.powermock.api.mockito.repackaged.*\"})\n@PrepareForTest(Foo.class)\n@MockPolicy(PowerMockRuleTest.CustomPolicy.class)\npublic class PowerMockRuleTest {\n\n    @Rule\n    public final PowerMockRule rule = new PowerMockRule();\n\n    @Test\n    public void test1() {\n        assertEquals(999, new Foo().m().getI());\n    }\n\n    @Test\n    public void test2() {\n        assertEquals(999, new Foo().m().getI());\n    }\n\n    public static class CustomPolicy implements PowerMockPolicy {\n\n        @Override\n        public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {\n        }\n\n        @Override\n        public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {\n            final Bar barMock = mock(Bar.class);\n            when(barMock.getI()).thenReturn(999);\n            settings.stubMethod(Whitebox.getMethod(Foo.class, \"m\"), barMock);\n        }\n    }\n\n}"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PrivateInstanceMockingTest.java",
    "content": "package samples.powermockito.junit4.rule.objenesis;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.powermockito.junit4.privatemocking.PrivateInstanceMockingCases;\nimport samples.privatemocking.PrivateMethodDemo;\n\n@PrepareForTest( { PrivateMethodDemo.class })\npublic class PrivateInstanceMockingTest extends PrivateInstanceMockingCases {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/StaticInitializerExampleTest.java",
    "content": "package samples.powermockito.junit4.rule.objenesis;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport org.powermock.reflect.Whitebox;\nimport samples.staticinitializer.StaticInitializerExample;\n\nimport java.util.HashSet;\n\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertSame;\n\n@SuppressStaticInitializationFor(\"samples.staticinitializer.StaticInitializerExample\")\npublic class StaticInitializerExampleTest {\n\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n\n\t@Test\n\tpublic void testSupressStaticInitializerAndSetFinalField() throws Exception {\n\t\tassertNull(\"Should be null because the static initializer should be suppressed\", StaticInitializerExample.getMySet());\n\t\tfinal HashSet<String> hashSet = new HashSet<String>();\n\t\tWhitebox.setInternalState(StaticInitializerExample.class, \"mySet\", hashSet);\n\t\tassertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, \"mySet\"));\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.objenesis;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.system.SystemClassUser;\n\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\nimport static org.mockito.Mockito.times;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.spy;\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n/**\n * Demonstrates PowerMockito's ability to mock non-final and final system\n * classes. To mock a system class you need to prepare the calling class for\n * testing. I.e. let's say you're testing class A which interacts with\n * URLEncoder then you would do:\n * <p>\n * <pre>\n *\n * &#064;PrepareForTest({A.class})\n *\n * </pre>\n */\n@PrepareForTest({SystemClassUser.class})\n@Ignore\npublic class SystemClassUserTest {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n    \n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n        \n        when(URLEncoder.encode(\"string\", \"enc\")).thenReturn(\"something\");\n        \n        assertEquals(\"something\", new SystemClassUser().performEncode());\n    }\n    \n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n        \n        Runtime runtimeMock = mock(Runtime.class);\n        Process processMock = mock(Process.class);\n        \n        when(Runtime.getRuntime()).thenReturn(runtimeMock);\n        when(runtimeMock.exec(\"command\")).thenReturn(processMock);\n        \n        assertSame(processMock, new SystemClassUser().executeCommand());\n    }\n    \n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n        \n        when(System.getProperty(\"property\")).thenReturn(\"my property\");\n        \n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n    }\n    \n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        spy(System.class);\n        \n        when(System.nanoTime()).thenReturn(2L);\n        \n        new SystemClassUser().doMoreComplicatedStuff();\n        \n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n    }\n    \n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n        \n        Collections.shuffle(list);\n        \n        new SystemClassUser().shuffleCollection(list);\n        \n        verifyStatic(Collections.class, times(2));\n        Collections.shuffle(list);\n    }\n    \n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        spy(System.class);\n        \n        when(System.getProperty(\"property\")).thenReturn(\"my property\");\n        \n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n    }\n    \n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n        \n        when(String.format(string, args)).thenReturn(returnValue);\n        \n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/WhenNewTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.objenesis;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.expectnew.ExpectNewDemo;\nimport samples.newmocking.MyClass;\nimport samples.powermockito.junit4.whennew.WhenNewCases;\n\nimport java.io.DataInputStream;\n\n/**\n * Test class to demonstrate new instance mocking using whenConstructionOf(..).\n * \n */\n@SuppressWarnings(\"PrimitiveArrayArgumentToVariableArgMethod\")\n@Ignore(\"Since upgrading to JVM 1.6.0_24 lots of tests started to fail\")\n@PrepareForTest({ MyClass.class, ExpectNewDemo.class, DataInputStream.class })\npublic class WhenNewTest extends WhenNewCases {\n\t@Rule\n\tpublic PowerMockRule powerMockRule = new PowerMockRule();\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/Github512Test.java",
    "content": "package samples.powermockito.junit4.rule.objenesis.bugs.github512;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.singleton.StaticService;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.method;\nimport static org.powermock.api.mockito.PowerMockito.suppress;\n\npublic class Github512Test {\n\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n\n    @Test\n    @PrepareForTest(StaticService.class)\n    public void shouldSuppressMethodWithPrepareForTestOnMethod() {\n        suppress(method(StaticService.class, \"calculate\"));\n        assertThat(StaticService.calculate(1, 5)).isEqualTo(0);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/package-info.java",
    "content": "/**\n *  https://github.com/jayway/powermock/issues/512\n */\npackage samples.powermockito.junit4.rule.objenesis.bugs.github512;"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/AssertPowerMockRuleDelagatesToOtherRulesTest.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.xstream;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.MethodRule;\nimport org.junit.rules.TestName;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\nimport org.powermock.core.classloader.MockClassLoader;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static junit.framework.Assert.assertTrue;\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.junit.Assert.assertEquals;\n\n/**\n * This test demonstrates that the PowerMockRule delegates to other rules.\n */\npublic class AssertPowerMockRuleDelagatesToOtherRulesTest {\n\tprivate static final MyObject BEFORE = new MyObject();\n\n\tprivate final List<Object> objects = new LinkedList<Object>();\n\n\t@Rule\n\tpublic PowerMockRule powerMockRule = new PowerMockRule();\n\n\t@Rule\n\tpublic MyRule rule = new MyRule();\n\n\t@Rule\n\tpublic TestName testName = new TestName();\n\n\t@Test\n\tpublic void assertPowerMockRuleDelegatesToOtherRules() throws Exception {\n\t\tassertThat(this.getClass().getClassLoader()).isInstanceOf(MockClassLoader.class);\n\t\t\n\t\tassertThat(objects)\n\t\t\t.hasSize(1)\n\t\t\t.containsExactly(BEFORE);\n\t\t\n\t\tassertThat(testName.getMethodName()).isEqualTo(\"assertPowerMockRuleDelegatesToOtherRules\");\n\t}\n\n\tprivate class MyRule implements MethodRule {\n\t\tpublic Statement apply(final Statement base, FrameworkMethod method, Object target) {\n\t\t\treturn new Statement() {\n\t\t\t\t@Override\n\t\t\t\tpublic void evaluate() throws Throwable {\n\t\t\t\t\tobjects.add(BEFORE);\n\t\t\t\t\tbase.evaluate();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n    private static class MyObject {\n        private final String state = \"state\";\n\n        @Override\n        public boolean equals(Object o) {\n            if (this == o) return true;\n            if (o == null || getClass() != o.getClass()) return false;\n\n            MyObject myObject = (MyObject) o;\n\n\t        return state.equals(myObject.state);\n        }\n\n        @Override\n        public int hashCode() {\n            return state.hashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/Foo.java",
    "content": "package samples.powermockito.junit4.rule.xstream;\n\npublic class Foo {\n\n\tpublic Bar m() {\n\t\treturn new Bar(1);\n\t}\n\n\t@SuppressWarnings(\"SameParameterValue\")\n\tpublic static class Bar {\n\n\t\tprivate final int i;\n\n\t\tBar(final int i) {\n\t\t\tthis.i = i;\n\t\t}\n\n\t\tpublic int getI() {\n\t\t\treturn i;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockFinalNonStaticMethodsTest.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.xstream;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.finalmocking.FinalDemo;\nimport samples.powermockito.junit4.finalmocking.MockFinalMethodsCases;\nimport samples.privateandfinal.PrivateFinal;\n\n/**\n * Test class to demonstrate non-static final mocking with Mockito.\n */\n@PrepareForTest( { FinalDemo.class, PrivateFinal.class })\npublic class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases{\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.xstream;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.powermockito.junit4.staticmocking.MockStaticCases;\nimport samples.singleton.SimpleStaticService;\nimport samples.singleton.StaticService;\n\n/**\n * Test class to demonstrate static mocking with PowerMockito.\n */\n@PrepareForTest({StaticService.class, SimpleStaticService.class})\npublic class MockStaticTest extends MockStaticCases {\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n    \n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PowerMockRuleTest.java",
    "content": "package samples.powermockito.junit4.rule.xstream;\n\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.MockPolicy;\nimport org.powermock.core.classloader.annotations.PowerMockIgnore;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.core.spi.PowerMockPolicy;\nimport org.powermock.mockpolicies.MockPolicyClassLoadingSettings;\nimport org.powermock.mockpolicies.MockPolicyInterceptionSettings;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport org.powermock.reflect.Whitebox;\nimport samples.powermockito.junit4.rule.xstream.Foo.Bar;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\n\n@PowerMockIgnore({\"org.mockito.*\",\"org.powermock.api.mockito.repackaged.*\"})\n@PrepareForTest(Foo.class)\n@MockPolicy(PowerMockRuleTest.CustomPolicy.class)\npublic class PowerMockRuleTest {\n\n    @Rule\n    public final PowerMockRule rule = new PowerMockRule();\n\n    @Test\n    public void test1() {\n        assertEquals(999, new Foo().m().getI());\n    }\n\n    @Test\n    public void test2() {\n        assertEquals(999, new Foo().m().getI());\n    }\n\n    public static class CustomPolicy implements PowerMockPolicy {\n\n        @Override\n        public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {\n        }\n\n        @Override\n        public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {\n            final Bar barMock = mock(Bar.class);\n            when(barMock.getI()).thenReturn(999);\n            settings.stubMethod(Whitebox.getMethod(Foo.class, \"m\"), barMock);\n        }\n    }\n\n}"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PrivateInstanceMockingTest.java",
    "content": "package samples.powermockito.junit4.rule.xstream;\n\nimport org.junit.Rule;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.powermockito.junit4.privatemocking.PrivateInstanceMockingCases;\nimport samples.privatemocking.PrivateMethodDemo;\n\n@PrepareForTest( { PrivateMethodDemo.class })\npublic class PrivateInstanceMockingTest extends PrivateInstanceMockingCases {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/StaticInitializerExampleTest.java",
    "content": "package samples.powermockito.junit4.rule.xstream;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport org.powermock.reflect.Whitebox;\nimport samples.staticinitializer.StaticInitializerExample;\n\nimport java.util.HashSet;\n\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertSame;\n\n@SuppressStaticInitializationFor(\"samples.staticinitializer.StaticInitializerExample\")\npublic class StaticInitializerExampleTest {\n\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n\n\t@Test\n\tpublic void testSupressStaticInitializerAndSetFinalField() throws Exception {\n\t\tassertNull(\"Should be null because the static initializer should be suppressed\", StaticInitializerExample.getMySet());\n\t\tfinal HashSet<String> hashSet = new HashSet<String>();\n\t\tWhitebox.setInternalState(StaticInitializerExample.class, \"mySet\", hashSet);\n\t\tassertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, \"mySet\"));\n\t}\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/SystemClassUserTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.xstream;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.system.SystemClassUser;\n\nimport java.net.URLEncoder;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\nimport static org.mockito.Mockito.times;\nimport static org.powermock.api.mockito.PowerMockito.mock;\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.spy;\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n/**\n * Demonstrates PowerMockito's ability to mock non-final and final system\n * classes. To mock a system class you need to prepare the calling class for\n * testing. I.e. let's say you're testing class A which interacts with\n * URLEncoder then you would do:\n * \n * <pre>\n * \n * &#064;PrepareForTest({A.class})\n * \n * </pre>\n */\n@PrepareForTest( { SystemClassUser.class })\n@Ignore\npublic class SystemClassUserTest {\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    @Test\n    public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {\n        mockStatic(URLEncoder.class);\n\n        when(URLEncoder.encode(\"string\", \"enc\")).thenReturn(\"something\");\n\n        assertEquals(\"something\", new SystemClassUser().performEncode());\n    }\n\n    @Test\n    public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception {\n        mockStatic(Runtime.class);\n\n        Runtime runtimeMock = mock(Runtime.class);\n        Process processMock = mock(Process.class);\n\n        when(Runtime.getRuntime()).thenReturn(runtimeMock);\n        when(runtimeMock.exec(\"command\")).thenReturn(processMock);\n\n        assertSame(processMock, new SystemClassUser().executeCommand());\n    }\n\n    @Test\n    public void assertThatMockingOfFinalSystemClassesWorks() throws Exception {\n        mockStatic(System.class);\n\n        when(System.getProperty(\"property\")).thenReturn(\"my property\");\n\n        assertEquals(\"my property\", new SystemClassUser().getSystemProperty());\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception {\n        spy(System.class);\n\n        when(System.nanoTime()).thenReturn(2L);\n\n        new SystemClassUser().doMoreComplicatedStuff();\n\n        assertEquals(\"2\", System.getProperty(\"nanoTime\"));\n    }\n\n    @Test\n    public void assertThatMockingOfCollectionsWork() throws Exception {\n        List<?> list = new LinkedList<Object>();\n        mockStatic(Collections.class);\n\n        Collections.shuffle(list);\n\n        new SystemClassUser().shuffleCollection(list);\n\n        verifyStatic(Collections.class, times(2));\n        Collections.shuffle(list);\n    }\n\n    @Test\n    public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception {\n        spy(System.class);\n\n        when(System.getProperty(\"property\")).thenReturn(\"my property\");\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        systemClassUser.copyProperty(\"to\", \"property\");\n    }\n\n    @Test\n    public void assertThatMockingStringWorks() throws Exception {\n        mockStatic(String.class);\n        final String string = \"string\";\n        final String args = \"args\";\n        final String returnValue = \"returnValue\";\n\n        when(String.format(string, args)).thenReturn(returnValue);\n\n        final SystemClassUser systemClassUser = new SystemClassUser();\n        assertEquals(systemClassUser.format(string, args), returnValue);\n    }\n}"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/WhenNewTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rule.xstream;\n\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.powermockito.junit4.whennew.WhenNewCases;\n\n\n/**\n * Test class to demonstrate new instance mocking using whenConstructionOf(..).\n * \n */\n@SuppressWarnings(\"PrimitiveArrayArgumentToVariableArgMethod\")\npublic class WhenNewTest extends WhenNewCases{\n\n    @Rule\n    public PowerMockRule powerMockRule = new PowerMockRule();\n\n    @Ignore(\"Test case fails only for xstream with MockitoException: Mockito cannot mock this class: \" +\n            \"class samples.classwithinnermembers.ClassWithInnerMembers$1MyLocalClass\")\n    @Test\n    @Override\n    public void testLocalClassMockingWorksWithNoConstructorArguments() throws Exception {\n        super.testLocalClassMockingWorksWithNoConstructorArguments();\n    }\n\n    @Ignore(\"Test case fails only for xstream with MockitoException: Mockito cannot mock this class: \" +\n            \"class samples.classwithinnermembers.ClassWithInnerMembers$2MyLocalClass\")\n    @Test\n    @Override\n    public void testLocalClassMockingWorksWithConstructorArguments() throws Exception {\n        super.testLocalClassMockingWorksWithConstructorArguments();\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/Github512Test.java",
    "content": "package samples.powermockito.junit4.rule.xstream.github512;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.rule.PowerMockRule;\nimport samples.singleton.StaticService;\n\nimport static org.assertj.core.api.Java6Assertions.assertThat;\nimport static org.powermock.api.mockito.PowerMockito.method;\nimport static org.powermock.api.mockito.PowerMockito.suppress;\n\npublic class Github512Test {\n\n    @Rule\n    public PowerMockRule rule = new PowerMockRule();\n\n    @Test\n    @PrepareForTest(StaticService.class)\n    public void shouldSuppressMethodWithPrepareForTestOnMethod() {\n        suppress(method(StaticService.class, \"calculate\"));\n        assertThat(StaticService.calculate(1, 5)).isEqualTo(0);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/package-info.java",
    "content": "/**\n *  https://github.com/jayway/powermock/issues/512\n */\npackage samples.powermockito.junit4.rule.xstream.github512;"
  },
  {
    "path": "tests/mockito/junit49/src/test/java/samples/powermockito/junit4/rules/JUnit49RuleTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.junit4.rules;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertSame;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TestName;\nimport org.junit.rules.TestRule;\nimport org.junit.runner.Description;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.model.Statement;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.junit4.PowerMockRunner;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * JUnit 4.9 changed the implementation/execution of Rules.\n * Demonstrates that <a\n * href=\"http://code.google.com/p/powermock/issues/detail?id=344\">issue 344</a>\n * is resolved.\n */\n@RunWith(PowerMockRunner.class)\n@PrepareForTest( { JUnit49RuleTest.class })\npublic class JUnit49RuleTest {\n\n    private static Object BEFORE = new Object();\n\n    private List<Object> objects = new LinkedList<Object>();\n\n    @Rule\n    public MyRule rule = new MyRule();\n\n    @Rule\n    public TestName testName = new TestName();\n\n    @Test\n    public void assertThatJUnit47RulesWorks() throws Exception {\n        assertEquals(1, objects.size());\n        assertSame(BEFORE, objects.get(0));\n        assertEquals(\"assertThatJUnit47RulesWorks\", testName.getMethodName());\n    }\n\n    private class MyRule implements TestRule {\n\n        @Override\n        public Statement apply(final Statement statement, Description description) {\n            return new Statement() {\n                @Override\n                public void evaluate() throws Throwable {\n                    objects.add(BEFORE);\n                    statement.evaluate();\n                }\n            };\n        }\n    }\n}"
  },
  {
    "path": "tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticNotPreparedTest.java",
    "content": "package samples.powermockito.testng.staticmocking;\r\n\r\nimport org.powermock.api.mockito.ClassNotPreparedException;\r\nimport org.powermock.modules.testng.PowerMockTestCase;\r\nimport org.testng.annotations.Test;\r\nimport samples.singleton.StaticService;\r\n\r\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\r\n\r\npublic class MockStaticNotPreparedTest extends PowerMockTestCase {\r\n    \r\n    @Test(expectedExceptions = ClassNotPreparedException.class)\r\n    public void should_throw_exception_if_class_not_prepared_for_test() throws Exception {\r\n\r\n        mockStatic(StaticService.class);\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticPreparedWithoutMockStaticTest.java",
    "content": "package samples.powermockito.testng.staticmocking;\r\n\r\nimport org.mockito.exceptions.misusing.MissingMethodInvocationException;\r\nimport org.powermock.core.classloader.annotations.PrepareForTest;\r\nimport org.powermock.modules.testng.PowerMockTestCase;\r\nimport org.testng.annotations.Test;\r\nimport samples.singleton.StaticService;\r\n\r\nimport static org.powermock.api.mockito.PowerMockito.when;\r\n\r\n\r\n@PrepareForTest(StaticService.class)\r\npublic class MockStaticPreparedWithoutMockStaticTest extends PowerMockTestCase {\r\n\r\n\r\n    //FIXME? Cannot override reporter in Mockito2 @Test(expectedExceptions = MissingMethodInvocationException.class, expectedExceptionsMessageRegExp = \"(?s).*PrepareForTest(?s).*\", enabled = false)\r\n    @Test(expectedExceptions = MissingMethodInvocationException.class, enabled = false)\r\n    public void testWhenNotPrepared() throws Exception {\r\n\r\n        when(StaticService.say(\"Hello\")).thenReturn(\"Hello World!\");\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockitoMockStaticTest.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.powermockito.testng.staticmocking;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockObjectFactory;\nimport org.testng.Assert;\nimport org.testng.IObjectFactory;\nimport org.testng.annotations.ObjectFactory;\nimport org.testng.annotations.Test;\nimport samples.singleton.StaticHelper;\nimport samples.singleton.StaticService;\n\nimport static org.powermock.api.mockito.PowerMockito.mockStatic;\nimport static org.powermock.api.mockito.PowerMockito.verifyStatic;\nimport static org.powermock.api.mockito.PowerMockito.when;\n\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n */\n@PrepareForTest({StaticService.class, StaticHelper.class})\npublic class MockitoMockStaticTest {\n    \n    @ObjectFactory\n    public IObjectFactory getObjectFactory() {\n        return new PowerMockObjectFactory();\n    }\n    \n    \n    @Test\n    public void testMockStatic() throws Exception {\n        \n        System.out.println(\"Skip test while Mockito doesn't deliver fix\");\n        \n        mockStatic(StaticService.class);\n        String expected = \"Hello altered World\";\n        when(StaticService.say(\"hello\")).thenReturn(\"Hello altered World\");\n        \n        String actual = StaticService.say(\"hello\");\n        \n        verifyStatic(StaticService.class);\n        StaticService.say(\"hello\");\n        \n        Assert.assertEquals(expected, actual);\n    }\n    \n    \n    @Test\n    public void testMockStaticFinal() throws Exception {\n        \n        System.out.println(\"Skip test while Mockito doesn't deliver fix\");\n        \n        mockStatic(StaticService.class);\n        String expected = \"Hello altered World\";\n        when(StaticService.sayFinal(\"hello\")).thenReturn(\"Hello altered World\");\n        \n        String actual = StaticService.sayFinal(\"hello\");\n        \n        verifyStatic(StaticService.class);\n        StaticService.sayFinal(\"hello\");\n        \n        Assert.assertEquals(expected, actual);\n    }\n}\n"
  },
  {
    "path": "tests/mockito/testng/src/test/java/samples/testng/bugs/github656/GitHub656Test.java",
    "content": "package samples.testng.bugs.github656;\n\nimport org.powermock.api.mockito.PowerMockito;\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.annotations.Test;\n\nimport static org.mockito.Mockito.verify;\n\n/**\n *\n */\n@PrepareForTest({ GitHub656Test.SimpleFoo.class })\npublic class GitHub656Test extends PowerMockTestCase {\n\n    @Test\n    public void should_be_only_one_invocation() {\n        GitHub656Test.SimpleFoo foo = PowerMockito.spy(new GitHub656Test.SimpleFoo());\n\n        foo.setFoo(\" \");\n\n        verify(foo).setFoo(\" \");\n    }\n\n    public static class SimpleFoo {\n\n        private String foo;\n\n        public void setFoo(String foo) {\n            this.foo = foo;\n        }\n\n        public String getFoo() {\n            return foo;\n        }\n    }\n\n}\n"
  },
  {
    "path": "tests/mockito/testng/src/test/java/samples/testng/bugs/github656/package-info.java",
    "content": "/**\n *  TooManyActualInvocations when class is prepared for test.\n *  https://github.com/jayway/powermock/issues/656\n */\npackage samples.testng.bugs.github656;"
  },
  {
    "path": "tests/mockito/testng/suite.xml",
    "content": "<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name=\"PowerMockito TestNG\" verbose=\"10\" object-factory=\"org.powermock.modules.testng.PowerMockObjectFactory\">\n    <test name=\"General\">\n        <classes>\n            <class name=\"samples.powermockito.testng.staticmocking.MockStaticNotPreparedTest\"/>\n            <class name=\"samples.powermockito.testng.staticmocking.MockStaticPreparedWithoutMockStaticTest\"/>\n        </classes>\n    </test>\n</suite>"
  },
  {
    "path": "tests/testng/src/test/java/samples/testng/SimpleBaseTest.java",
    "content": "package samples.testng;\n\nimport org.testng.Assert;\nimport org.testng.ITestResult;\nimport org.testng.TestListenerAdapter;\nimport org.testng.TestNG;\nimport org.testng.collections.Lists;\nimport org.testng.xml.XmlClass;\nimport org.testng.xml.XmlInclude;\nimport org.testng.xml.XmlSuite;\nimport org.testng.xml.XmlTest;\n\nimport java.io.File;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class SimpleBaseTest {\n\n    private static final String TEST_RESOURCES_DIR = \"test.resources.dir\";\n\n    public static TestNG create() {\n        TestNG result = new TestNG();\n        result.setUseDefaultListeners(false);\n        result.setVerbose(0);\n        return result;\n    }\n\n    public static TestNG create(Class<?>... testClasses) {\n        TestNG result = create();\n        result.setTestClasses(testClasses);\n        return result;\n    }\n\n    public static String getPathToResource(String fileName) {\n        String result = System.getProperty(TEST_RESOURCES_DIR);\n        if (result == null) {\n            throw new IllegalArgumentException(\"System property \" + TEST_RESOURCES_DIR + \" was not defined.\");\n        }\n        return result + File.separatorChar + fileName;\n    }\n\n    /**\n     * Compare a list of ITestResult with a list of String method names,\n     */\n    public static void assertTestResultsEqual(List<ITestResult> results, List<String> methods) {\n        List<String> resultMethods = Lists.newArrayList();\n        for (ITestResult r : results) {\n            resultMethods.add(r.getMethod().getMethodName());\n        }\n        Assert.assertEquals(resultMethods, methods);\n    }\n\n    protected TestNG create(XmlSuite... suites) {\n        TestNG result = create();\n        result.setXmlSuites(Arrays.asList(suites));\n        return result;\n    }\n\n    protected TestNG createTests(String suiteName, Class<?>... testClasses) {\n        XmlSuite suite = createXmlSuite(suiteName);\n        int i = 0;\n        for (Class<?> testClass : testClasses) {\n            createXmlTest(suite, testClass.getName() + i, testClass);\n            i++;\n        }\n        return create(suite);\n    }\n\n    protected XmlSuite createXmlSuite(String name) {\n        XmlSuite result = new XmlSuite();\n        result.setName(name);\n        return result;\n    }\n\n    protected XmlTest createXmlTest(XmlSuite suite, String name, Class clazz, Class... classes) {\n        XmlTest result = new XmlTest(suite);\n        int index = 0;\n        result.setName(name);\n        XmlClass xc = new XmlClass(clazz.getName(), index++, true /* load classes */);\n        result.getXmlClasses().add(xc);\n        for (Class c : classes) {\n            xc = new XmlClass(c.getName(), index++, true /* load classes */);\n            result.getXmlClasses().add(xc);\n        }\n\n        return result;\n    }\n\n    protected XmlTest createXmlTest(XmlSuite suite, String name, String... classes) {\n        XmlTest result = new XmlTest(suite);\n        int index = 0;\n        result.setName(name);\n        for (String c : classes) {\n            XmlClass xc = new XmlClass(c, index++, true /* load classes */);\n            result.getXmlClasses().add(xc);\n        }\n\n        return result;\n    }\n\n    protected void addMethods(XmlClass cls, String... methods) {\n        int index = 0;\n        for (String m : methods) {\n            XmlInclude include = new XmlInclude(m, index++);\n            cls.getIncludedMethods().add(include);\n        }\n    }\n\n    protected void verifyPassedTests(TestListenerAdapter tla, String... methodNames) {\n        Iterator<ITestResult> it = tla.getPassedTests().iterator();\n        Assert.assertEquals(tla.getPassedTests().size(), methodNames.length);\n\n        int i = 0;\n        while (it.hasNext()) {\n            Assert.assertEquals(it.next().getName(), methodNames[i++]);\n        }\n    }\n\n}\n"
  },
  {
    "path": "tests/testng/src/test/java/samples/testng/bugs/github647/GitHub647.java",
    "content": "package samples.testng.bugs.github647;\n\nimport org.testng.IResultMap;\nimport org.testng.TestListenerAdapter;\nimport org.testng.TestNG;\nimport org.testng.annotations.Test;\nimport org.testng.xml.XmlSuite;\nimport samples.testng.SimpleBaseTest;\n\nimport java.net.URL;\nimport java.net.URLClassLoader;\n\nimport static org.testng.Assert.assertEquals;\n\npublic class GitHub647 extends SimpleBaseTest {\n\n  private final TestListenerAdapter tla;\n\n  public GitHub647() {\n    tla = new TestListenerAdapter();\n  }\n\n  @Test\n  public void testSkipTest() throws Exception {\n\n    final TestNG tng = createTestNG();\n\n    runTest(tng);\n\n    assertOneTestSkipped();\n  }\n\n  private TestNG createTestNG() {\n    final TestNG tng = create(SkipExceptionTest.class);\n    tng.setThreadCount(1);\n    tng.setParallel(XmlSuite.ParallelMode.NONE);\n    tng.setPreserveOrder(true);\n    tng.addListener(tla);\n    return tng;\n  }\n\n  private void assertOneTestSkipped() {\n    IResultMap skippedTests = tla.getTestContexts().get(0).getSkippedTests();\n    assertEquals(1, skippedTests.size());\n  }\n\n  private void runTest(TestNG tng) {\n\n    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();\n    ClassLoader classLoader = new SimpleClassLoader(currentClassLoader);\n\n    Thread.currentThread().setContextClassLoader(classLoader);\n\n    tng.run();\n\n    Thread.currentThread().setContextClassLoader(currentClassLoader);\n  }\n\n  public static final class SimpleClassLoader extends ClassLoader {\n\n    private final ClassLoader currentClassLoader;\n    private final URLClassLoader delegate;\n\n    public SimpleClassLoader(ClassLoader currentClassLoader) {\n      this.currentClassLoader = currentClassLoader;\n      this.delegate = new URLClassLoader(new URL[]{currentClassLoader.getResource(\"\")}, null);\n    }\n\n\n    @Override\n    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {\n      final Class<?> clazz;\n\n      if (shouldBeLoadedWithDelegate(name)) {\n        clazz = delegate.loadClass(name);\n      } else {\n        clazz = currentClassLoader.loadClass(name);\n      }\n\n      if (resolve) {\n        resolveClass(clazz);\n      }\n\n      return clazz;\n    }\n\n    private boolean shouldBeLoadedWithDelegate(String name) {\n      return \"org.testng.SkipException\".equals(name) || \"test.testng1003.SkipExceptionTest\".equals(name) ||\n                 \"test.testng1003.SomeClass\".equals(name);\n    }\n\n  }\n}\n"
  },
  {
    "path": "tests/testng/src/test/java/samples/testng/bugs/github647/SkipExceptionTest.java",
    "content": "package samples.testng.bugs.github647;\n\nimport org.powermock.core.classloader.annotations.PrepareForTest;\nimport org.powermock.modules.testng.PowerMockTestCase;\nimport org.testng.annotations.Test;\n\n/**\n *\n */\n@PrepareForTest(SomeClass.class)\npublic class SkipExceptionTest extends PowerMockTestCase{\n\n    @Test\n    public void testSkipException() throws Throwable {\n        new SomeClass().throwSkipException();\n    }\n}\n"
  },
  {
    "path": "tests/testng/src/test/java/samples/testng/bugs/github647/SomeClass.java",
    "content": "package samples.testng.bugs.github647;\n\nimport org.testng.SkipException;\n\n/**\n *\n */\npublic class SomeClass {\n    public void throwSkipException() {\n        throw new SkipException(\"Skip test\");\n    }\n}\n"
  },
  {
    "path": "tests/testng/suite.xml",
    "content": "<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name=\"TestNG\" verbose=\"10\" object-factory=\"org.powermock.modules.testng.PowerMockObjectFactory\">\n    <test name=\"TestNG Skip test Bug #647\">\n        <classes>\n            <class name=\"samples.testng.bugs.github647.GitHub647\"/>\n        </classes>\n    </test>\n</suite>"
  },
  {
    "path": "tests/utils/src/main/java/org/powermock/api/mockito/ConfigurationTestUtils.java",
    "content": "/*\n *\n *   Copyright 2017 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.net.URL;\n\nimport static org.powermock.utils.IOUtils.copyFileUsingStream;\n\npublic final class ConfigurationTestUtils {\n    \n    private static final String CONFIG_FILE = \"configuration.properties\";\n    \n    private File config;\n    \n    public void copyTemplateToPropertiesFile() throws URISyntaxException, IOException {\n        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n        URL resource = classLoader.getResource(\"org/powermock/extensions/configuration.template\");\n        \n        File file = new File(resource.toURI());\n        \n        File parentFile = file.getParentFile();\n        \n        config = new File(parentFile.getAbsolutePath() + File.separator + CONFIG_FILE);\n        \n        if (!config.createNewFile()) {\n            throw new AssertionError(\"Test data not created: cannot create \" + CONFIG_FILE);\n        }\n        \n        copyFileUsingStream(file, config);\n    }\n    \n    public void clear(){\n        if (config != null && !config.delete()){\n            throw new RuntimeException(\"Cannot delete temporary configuration.\");\n        }\n    }\n    \n}\n"
  },
  {
    "path": "tests/utils/src/main/java/org/powermock/api/mockito/MockitoVersion.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage org.powermock.api.mockito;\n\nimport java.security.CodeSource;\nimport java.security.ProtectionDomain;\n\npublic class MockitoVersion {\n    \n    public static boolean isMockito1(){\n        return MOCKITO_VERSION.isMockito1_0();\n    }\n\n    public static boolean isMockito2(){\n        return MOCKITO_VERSION.isMockito2_0();\n    }\n\n    public static boolean isMockito3(){\n        return MOCKITO_VERSION.isMockito3_0();\n    }\n\n    public static boolean isMockito4(){\n        return MOCKITO_VERSION.isMockito4_0();\n    }\n\n    private static final MockitoVersion MOCKITO_VERSION = new MockitoVersion();\n    \n    private final String version;\n    \n    private MockitoVersion() {\n        String ver = \"\";\n        try {\n            Class<?> mockitoClass = Class.forName(\"org.mockito.Mock\");\n            ProtectionDomain protectionDomain = mockitoClass.getProtectionDomain();\n            CodeSource codeSource = protectionDomain.getCodeSource();\n            String path = codeSource.getLocation().toString();\n            int x = path.lastIndexOf(\"-\");\n            int y = path.lastIndexOf(\".\");\n            ver = path.substring(x + 1, y);\n        } catch (Exception e) {\n            ver = \"\";\n        } finally {\n            version = ver;\n        }\n    }\n    \n    \n    private boolean isMockito1_0() {\n            return version.startsWith(\"1\");\n        }\n    \n    private boolean isMockito2_0() {\n        return version.startsWith(\"2\");\n    }\n\n    private boolean isMockito3_0() {\n        return version.startsWith(\"3\");\n    }\n\n    private boolean isMockito4_0() {\n        return version.startsWith(\"4\");\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/Service.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples;\n\n/**\n * A very simple service interface used as a dependency for various classes to\n * demonstrate different kinds of mocking.\n * \n * @author Johan Haleby\n */\npublic interface Service {\n\n\tpublic String getServiceMessage();\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/abstractmocking/AbstractMethodMocking.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.abstractmocking;\r\n\r\n/**\r\n * Demonstrates that PowerMock can mock abstract methods. This was previously a\r\n * bug in PowerMock.\r\n */\r\npublic abstract class AbstractMethodMocking {\r\n\r\n\tpublic String getValue() {\r\n\t\treturn getIt();\r\n\t}\r\n\r\n\tprotected abstract String getIt();\r\n\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/annotationbased/AnnotatedClassDemo.java",
    "content": "package samples.annotationbased;\n\nimport samples.annotationbased.testannotations.RuntimeAnnotation;\n\n@RuntimeAnnotation\npublic class AnnotatedClassDemo {\n    public static boolean staticMethod() {\n        return false;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/annotationbased/AnnotationDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.annotationbased;\r\n\r\nimport samples.Service;\r\n\r\npublic class AnnotationDemo {\r\n\r\n\tprivate Service service;\r\n\r\n\tpublic AnnotationDemo(Service service) {\r\n\t\tthis.service = service;\r\n\t}\r\n\r\n\tpublic AnnotationDemo() {\r\n\r\n\t}\r\n\r\n\tpublic String getServiceMessage() {\r\n\t\treturn service.getServiceMessage();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/annotationbased/testannotations/RuntimeAnnotation.java",
    "content": "package samples.annotationbased.testannotations;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport static java.lang.annotation.ElementType.TYPE;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Target(value = {TYPE})\npublic @interface RuntimeAnnotation {\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/anonymousmocking/MyAbstractClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.anonymousmocking;\n\npublic abstract class MyAbstractClass {\n\tpublic abstract String getMessage();\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/anonymousmocking/StupidAnonymous.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.anonymousmocking;\n\nimport samples.Service;\n\npublic class StupidAnonymous {\n\n\t// TODO We need to make sure that you also can mock private members from an\n\t// inner class!\n\tprotected Service service;\n\n\tpublic void setService(Service service) {\n\t\tthis.service = service;\n\t}\n\n\tpublic String getMessageFromMyClass() {\n\n\t\tMyAbstractClass myclass = new MyAbstractClass() {\n\t\t\t@Override\n\t\t\tpublic String getMessage() {\n\t\t\t\treturn \"Hello world!\";\n\t\t\t}\n\t\t};\n\n\t\treturn myclass.getMessage();\n\t}\n\n\tpublic String getMessagesFromSeveralInnerClasses() {\n\n\t\tMyAbstractClass myclass1 = new MyAbstractClass() {\n\t\t\t@Override\n\t\t\tpublic String getMessage() {\n\t\t\t\treturn \"Hello world 1!\";\n\t\t\t}\n\t\t};\n\n\t\tMyAbstractClass myclass2 = new MyAbstractClass() {\n\t\t\t@Override\n\t\t\tpublic String getMessage() {\n\t\t\t\treturn \"Hello world 2!\";\n\t\t\t}\n\t\t};\n\t\treturn myclass1.getMessage() + \" \" + myclass2.getMessage();\n\t}\n\n\tpublic String getServiceMessageFromInnerClass() {\n\n\t\tMyAbstractClass myclass = new MyAbstractClass() {\n\t\t\t@Override\n\t\t\tpublic String getMessage() {\n\t\t\t\treturn service.getServiceMessage();\n\t\t\t}\n\t\t};\n\n\t\treturn myclass.getMessage();\n\t}\n\n\tpublic String getMessageFromOtherMethodInInnerClass() {\n\n\t\tMyAbstractClass myclass = new MyAbstractClass() {\n\t\t\t@Override\n\t\t\tpublic String getMessage() {\n\t\t\t\treturn returnThisMessage();\n\t\t\t}\n\n\t\t\tpublic String returnThisMessage() {\n\t\t\t\treturn \"A message\";\n\t\t\t}\n\t\t};\n\n\t\treturn myclass.getMessage();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/argumentmatcher/ArgumentMatcherDemo.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.argumentmatcher;\n\nimport java.util.List;\n\npublic class ArgumentMatcherDemo {\n\n    public List<String> findByNamedQuery(String argument, List<String> someList) {\n        someList.add(\"one\");\n        return someList;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/classhierarchy/ChildA.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.classhierarchy;\n\npublic class ChildA extends Parent {\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/classhierarchy/ChildB.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.classhierarchy;\n\npublic class ChildB extends Parent {\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/classhierarchy/Parent.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.classhierarchy;\n\npublic class Parent {\n\tprivate int value;\n\n\tpublic int getValue() {\n\t\treturn value;\n\t}\n\n\tpublic void setValue(int value) {\n\t\tthis.value = value;\n\t}\n\t\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/classwithinnermembers/ClassWithInnerMembers.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.classwithinnermembers;\r\n\r\n/**\r\n * Class that is used to test that local and member class works with PowerMock.\r\n */\r\npublic class ClassWithInnerMembers {\r\n\r\n    private interface InnerInterface {\r\n        String doStuff();\r\n    }\r\n\r\n    public static class MyInnerClassWithPrivateConstructorWithDiffMultArgs {\r\n\r\n        private String mArg1;\r\n        private int mArg2;\r\n        private String mArg3;\r\n\r\n        private MyInnerClassWithPrivateConstructorWithDiffMultArgs(String arg1, int arg2, String arg3) {\r\n            mArg1 = arg1;\r\n            mArg2 = arg2;\r\n            mArg3 = arg3;\r\n        }\r\n    }\r\n\r\n    public MyInnerClassWithPrivateConstructorWithDiffMultArgs makeMyInnerClassWithPrivateConstructorWithDiffMultArgs(\r\n            String arg1, int arg2, String arg3) {\r\n        return new MyInnerClassWithPrivateConstructorWithDiffMultArgs(arg1, arg2, arg3);\r\n    }\r\n\r\n    public static class MyInnerClassWithPrivateConstructorWithMultArgs {\r\n\r\n        private String mArg1;\r\n        private String mArg2;\r\n        private String mArg3;\r\n\r\n        private MyInnerClassWithPrivateConstructorWithMultArgs(String arg1, String arg2, String arg3) {\r\n            mArg1 = arg1;\r\n            mArg2 = arg2;\r\n            mArg3 = arg3;\r\n        }\r\n    }\r\n\r\n    public MyInnerClassWithPrivateConstructorWithMultArgs makeMyInnerClassWithPrivateConstructorWithMultArgs(\r\n            String arg1, String arg2, String arg3) {\r\n        return new MyInnerClassWithPrivateConstructorWithMultArgs(arg1, arg2, arg3);\r\n    }\r\n\r\n    public static class MyInnerClassWithPublicConstructorWithMultArgs {\r\n\r\n        private String mArg1;\r\n        private String mArg2;\r\n        private String mArg3;\r\n\r\n        private MyInnerClassWithPublicConstructorWithMultArgs(String arg1, String arg2, String arg3) {\r\n            mArg1 = arg1;\r\n            mArg2 = arg2;\r\n            mArg3 = arg3;\r\n        }\r\n    }\r\n\r\n    public MyInnerClassWithPublicConstructorWithMultArgs makeMyInnerClassWithPublicConstructorWithMultArgs(\r\n            String arg1, String arg2, String arg3) {\r\n        return new MyInnerClassWithPublicConstructorWithMultArgs(arg1, arg2, arg3);\r\n    }\r\n\r\n    public static class MyInnerClassWithPackageConstructorWithMultArgs {\r\n\r\n        private String mArg1;\r\n        private String mArg2;\r\n        private String mArg3;\r\n\r\n        MyInnerClassWithPackageConstructorWithMultArgs(String arg1, String arg2, String arg3) {\r\n            mArg1 = arg1;\r\n            mArg2 = arg2;\r\n            mArg3 = arg3;\r\n        }\r\n    }\r\n\r\n    public MyInnerClassWithPackageConstructorWithMultArgs makeMyInnerClassWithPackageConstructorWithMultArgs(\r\n            String arg1, String arg2, String arg3) {\r\n        return new MyInnerClassWithPackageConstructorWithMultArgs(arg1, arg2, arg3);\r\n    }\r\n\r\n    public static class MyInnerClassWithProtectedConstructorWithMultArgs {\r\n\r\n        private String mArg1;\r\n        private String mArg2;\r\n        private String mArg3;\r\n\r\n        MyInnerClassWithProtectedConstructorWithMultArgs(String arg1, String arg2, String arg3) {\r\n            mArg1 = arg1;\r\n            mArg2 = arg2;\r\n            mArg3 = arg3;\r\n        }\r\n    }\r\n\r\n    public MyInnerClassWithProtectedConstructorWithMultArgs makeMyInnerClassWithProtectedConstructorWithMultArgs(\r\n            String arg1, String arg2, String arg3) {\r\n        return new MyInnerClassWithProtectedConstructorWithMultArgs(arg1, arg2, arg3);\r\n    }\r\n\r\n    private static class MyInnerClass implements InnerInterface {\r\n\r\n        @Override\r\n        public String doStuff() {\r\n            return \"member class\";\r\n        }\r\n    }\r\n\r\n    private static class StaticInnerClassWithConstructorArgument implements InnerInterface {\r\n\r\n        private final String value;\r\n\r\n        public StaticInnerClassWithConstructorArgument(String value) {\r\n            this.value = value;\r\n        }\r\n\r\n        @Override\r\n        public String doStuff() {\r\n            return value;\r\n        }\r\n    }\r\n\r\n    private class MyInnerClassWithConstructorArgument implements InnerInterface {\r\n\r\n        private final String value;\r\n\r\n        public MyInnerClassWithConstructorArgument(String value) {\r\n            this.value = value;\r\n        }\r\n\r\n        @Override\r\n        public String doStuff() {\r\n            return value;\r\n        }\r\n    }\r\n\r\n    public String getValue() {\r\n        return new MyInnerClass().doStuff();\r\n    }\r\n\r\n    public String getValueForInnerClassWithConstructorArgument() {\r\n        return new MyInnerClassWithConstructorArgument(\"value\").doStuff();\r\n    }\r\n\r\n    public String getValueForStaticInnerClassWithConstructorArgument() {\r\n        return new StaticInnerClassWithConstructorArgument(\"value\").doStuff();\r\n    }\r\n\r\n    public String getLocalClassValue() {\r\n        class MyLocalClass implements InnerInterface {\r\n            @Override\r\n            public String doStuff() {\r\n                return \"local class\";\r\n            }\r\n        }\r\n\r\n        return new MyLocalClass().doStuff();\r\n    }\r\n\r\n    public String getLocalClassValueWithArgument() {\r\n        class MyLocalClass implements InnerInterface {\r\n\r\n            private final String value;\r\n\r\n            public MyLocalClass(String value) {\r\n                this.value = value;\r\n            }\r\n\r\n            @Override\r\n            public String doStuff() {\r\n                return value;\r\n            }\r\n        }\r\n\r\n        return new MyLocalClass(\"my value\").doStuff();\r\n    }\r\n\r\n    public String getValueForAnonymousInnerClass() {\r\n\r\n        InnerInterface inner = new InnerInterface() {\r\n\r\n            @Override\r\n            public String doStuff() {\r\n                return \"value\";\r\n            }\r\n        };\r\n\r\n        return inner.doStuff();\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/constructor/PrivateConstructorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.constructor;\n\nimport samples.Service;\n\n/**\n * Demonstrates the ability to invoke a test on a private constructor as well as\n * lazy initialization of private collaborators.\n * \n * @author Johan Haleby\n */\npublic class PrivateConstructorDemo {\n\n\tprivate Service privateService;\n\n\tprivate String constructorResult;\n\n\tprivate PrivateConstructorDemo(String completeName) {\n\t\tconstructorResult = privateService.getServiceMessage() + completeName;\n\t}\n\n\tpublic String getConstructorResult() {\n\t\treturn constructorResult;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/constructor/PrivateConstructorInstantiationDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.constructor;\n\n/**\n * Class used to demonstrate the private constructor instantiation.\n * \n * @author Johan Haleby\n */\npublic class PrivateConstructorInstantiationDemo {\n\n\tprivate final int state;\n\n\tprivate PrivateConstructorInstantiationDemo() {\n\t\tthis(42);\n\t}\n\n\tprivate PrivateConstructorInstantiationDemo(int state) {\n\t\tthis.state = state;\n\t}\n\n\tpublic int getState() {\n\t\treturn state;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/constructor/PublicConstructorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.constructor;\n\nimport samples.Service;\n\n/**\n * Demonstrates the ability to invoke a test on a private constructor as well as\n * lazy initialization of private collaborators.\n * \n * @author Johan Haleby\n */\npublic class PublicConstructorDemo {\n\n\tprivate Service privateService;\n\n\tprivate String constructorResult;\n\n\tpublic PublicConstructorDemo(String completeName) {\n\t\tconstructorResult = privateService.getServiceMessage() + completeName;\n\t}\n\n\tpublic String getConstructorResult() {\n\t\treturn constructorResult;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/constructor/PublicConstructorWithDependencyDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.constructor;\r\n\r\nimport samples.Service;\r\n\r\n/**\r\n * This class is used to demonstrate that error messages are correct when a\r\n * constructor is not found.\r\n */\r\npublic class PublicConstructorWithDependencyDemo {\r\n\r\n\tprivate final Service service;\r\n\r\n\tpublic PublicConstructorWithDependencyDemo(Service service) {\r\n\t\tthis.service = service;\r\n\t}\r\n\r\n\tpublic Service getService() {\r\n\t\treturn service;\r\n\t}\r\n\r\n\tpublic void aMethod() {\r\n\t\tSystem.out.println(\"Does basically nothing\");\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/constructorargs/ConstructorArgsDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.constructorargs;\r\n\r\npublic class ConstructorArgsDemo {\r\n\r\n\tprivate static final String DEFAULT = \"default\";\r\n\r\n\tprivate final String secret;\r\n\r\n\tpublic ConstructorArgsDemo(String secret) {\r\n\t\tthis.secret = secret;\r\n\t}\r\n\r\n\tpublic ConstructorArgsDemo() {\r\n\t\tsecret = DEFAULT;\r\n\t}\r\n\r\n\tpublic String getTheSecret() {\r\n\t\treturn theSecretIsPrivate();\r\n\t}\r\n\r\n\tprivate String theSecretIsPrivate() {\r\n\t\treturn secret;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/enummocking/AnotherSomeObjectInterfaceImpl.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.enummocking;\n\n/**\n *\n */\npublic class AnotherSomeObjectInterfaceImpl implements SomeObjectInterface {\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/enummocking/EnumWithConstructor.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.enummocking;\n\n/**\n *\n */\npublic enum EnumWithConstructor {\n\n    SOME_ENUM_VALUE(\n\n    ) {\n        @Override\n        public SomeObjectInterface create() {\n            return new SomeObjectInterfaceImpl();\n        }\n    };\n\n    public abstract SomeObjectInterface create();\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/enummocking/MyEnum.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.enummocking;\r\n\r\npublic enum MyEnum {\r\n\r\n\tMY_VALUE;\r\n\t\r\n\tpublic static String getString() {\r\n\t\treturn MY_VALUE.toString();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/enummocking/SomeObjectInterface.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.enummocking;\n\n/**\n *\n */\npublic interface SomeObjectInterface {\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/enummocking/SomeObjectInterfaceImpl.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.enummocking;\n\n/**\n *\n */\npublic class SomeObjectInterfaceImpl implements SomeObjectInterface {\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/equalswithgetclass/EqualsWithGetClass.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.equalswithgetclass;\n\n/**\n * Class that implements an equals method that contains a call to getClass();\n */\npublic class EqualsWithGetClass {\n\n    private final String myString;\n\n    public EqualsWithGetClass(String myString) {\n        super();\n        this.myString = myString;\n    }\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + ((myString == null) ? 0 : myString.hashCode());\n        return result;\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj)\n            return true;\n        if (obj == null)\n            return false;\n        if (getClass() != obj.getClass())\n            return false;\n        EqualsWithGetClass other = (EqualsWithGetClass) obj;\n        if (myString == null) {\n            if (other.myString != null)\n                return false;\n        } else if (!myString.equals(other.myString))\n            return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/CreationException.java",
    "content": "package samples.expectnew;\n\n/**\n *\n */\npublic class CreationException extends RuntimeException {\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/ExpectNewDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.expectnew;\n\nimport samples.Service;\nimport samples.newmocking.MyClass;\n\nimport java.io.*;\nimport java.util.Date;\n\npublic class ExpectNewDemo {\n\n\tprivate int dummyField;\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + dummyField;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tfinal ExpectNewDemo other = (ExpectNewDemo) obj;\n\t\tif (dummyField != other.dummyField)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic String getMessage() {\n\t\tMyClass myClass = new MyClass();\n\t\treturn myClass.getMessage();\n\t}\n\n\tpublic String getMessageWithArgument() {\n\t\tMyClass myClass = new MyClass();\n\t\treturn myClass.getMessage(\"test\");\n\t}\n\n\tpublic void invokeVoidMethod() {\n\t\tMyClass myClass = new MyClass();\n\t\tmyClass.voidMethod();\n\t}\n\n\t/**\n\t * The purpose of the method is to demonstrate that a test case can mock the\n\t * new instance call and throw an exception upon instantiation.\n\t */\n\tpublic void throwExceptionWhenInvoction() {\n\t\tnew MyClass();\n\t}\n\n\t/**\n\t * The purpose of the method is to demonstrate that a test case can mock the\n\t * new instance call and throw an exception upon instantiation.\n\t */\n\tpublic void throwExceptionAndWrapInRunTimeWhenInvoction() {\n\t\ttry {\n\t\t\tnew MyClass();\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e.getMessage(), e);\n\t\t}\n\t}\n\n\tpublic String multipleNew() {\n\t\tMyClass myClass1 = new MyClass();\n\t\tMyClass myClass2 = new MyClass();\n\n\t\tfinal String message1 = myClass1.getMessage();\n\t\tfinal String message2 = myClass2.getMessage();\n\t\treturn message1 + message2;\n\t}\n\n\tpublic void simpleMultipleNew() {\n\t\tnew MyClass();\n\t\tnew MyClass();\n\t\tnew MyClass();\n\t}\n\n\t@SuppressWarnings(\"unused\")\n\tprivate void simpleMultipleNewPrivate() {\n\t\tnew MyClass();\n\t\tnew MyClass();\n\t\tnew MyClass();\n\t}\n\n\tpublic void simpleSingleNew() {\n\t\tnew MyClass();\n\t}\n\n\tpublic Date makeDate() {\n\t\treturn new Date();\n\t}\n\t\n\tpublic boolean fileExists(String name) {\n\t\treturn new File(name).exists();\n\t}\n\n\tpublic InputStream alternativePath() {\n\t\ttry {\n\t\t\treturn new DataInputStream(null);\n\t\t} catch (RuntimeException e) {\n\t\t\treturn new ByteArrayInputStream(new byte[0]);\n\t\t}\n\t}\n\n\tpublic String newWithArguments(Service service, int times) {\n\t\treturn new ExpectNewServiceUser(service, times).useService();\n\t}\n\n\tpublic String newWithWrongArguments(Service service, int times) {\n\t\treturn new ExpectNewServiceUser(service, times * 2).useService();\n\t}\n\n\tpublic String[] newVarArgs(String... strings) {\n\t\treturn new VarArgsConstructorDemo(strings).getAllMessages();\n\t}\n\n\tpublic Service[] newVarArgs(Service... services) {\n\t\treturn new VarArgsConstructorDemo(services).getAllServices();\n\t}\n    public int[] newVarArgs(float myFloat, int ... ints) {\n\t\treturn new VarArgsConstructorDemo(myFloat, ints).getInts();\n\t}\n\n\tpublic byte[][] newVarArgs(byte[]... bytes) {\n\t\treturn new VarArgsConstructorDemo(bytes).getByteArrays();\n\t}\n\n\tpublic byte[][] newVarArgsWithMatchers() {\n\t\treturn new VarArgsConstructorDemo(new byte[] { 42 }, new byte[] { 17 }).getByteArrays();\n\t}\n\n\tpublic void fileWriter(String name, String msg) throws IOException {\n\t\tnew FileWriter(name).write(msg);\n\t}\n\n\tpublic void fileWriterPrint(String name, String msg) throws IOException {\n\t\tnew PrintWriter(new FileWriter(name)).write(msg);\n\t}\n\n\tpublic byte[][] newSimpleVarArgs(byte[]... bytes) {\n\t\treturn new SimpleVarArgsConstructorDemo(bytes).getByteArrays();\n\t}\n\n    public Target createTarget(ITarget target) {\n        Target domainTarget;\n        try {\n            domainTarget = new Target(getTargetName(target), target.getId());\n        } catch (CreationException e) {\n            domainTarget = new Target(\"Unknown\", -1);\n        }\n        return domainTarget;\n    }\n\n    private String getTargetName(ITarget target) {\n        return target.getName();\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/ExpectNewOfFinalSystemClassDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.expectnew;\n\npublic class ExpectNewOfFinalSystemClassDemo {\n\n    public char getFirstChar() {\n        String myString = new String(\"My String\");\n        return myString.charAt(0);\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/ExpectNewServiceUser.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.expectnew;\r\n\r\nimport samples.Service;\r\n\r\npublic class ExpectNewServiceUser {\r\n\r\n\tprivate final Service service;\r\n\tprivate final int times;\r\n\r\n\tExpectNewServiceUser(Service service, int times) {\r\n\t\tthis.service = service;\r\n\t\tthis.times = times;\r\n\t}\r\n\r\n\tpublic String useService() {\r\n\t\tStringBuilder builder = new StringBuilder();\r\n\t\tfor (int i = 0; i < times; i++) {\r\n\t\t\tbuilder.append(service.getServiceMessage());\r\n\t\t}\r\n\t\treturn builder.toString();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/ExpectNewWithMultipleCtorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.expectnew;\n\nimport samples.Service;\n\npublic class ExpectNewWithMultipleCtorDemo {\n\n    private final Service service;\n    private final int times;\n\n    public ExpectNewWithMultipleCtorDemo(Service service) {\n        this(service, 1);\n    }\n\n    public ExpectNewWithMultipleCtorDemo(Service service, int times) {\n        this.service = service;\n        this.times = times;\n    }\n\n    public String useService() {\n        StringBuilder builder = new StringBuilder();\n        for (int i = 0; i < times; i++) {\n            builder.append(service.getServiceMessage());\n        }\n        return builder.toString();\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/ITarget.java",
    "content": "package samples.expectnew;\n\n/**\n *\n */\npublic interface ITarget {\n    int getId();\n\n    String getName();\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/MultiConstructor.java",
    "content": "package samples.expectnew;\n\n/**\n * Mocking object construction with {@code withAnyArguments()} does not treat all\n * the object's constructors equally. This test fixture provides an object which\n * has multiple constructors so that tests can cover both code-paths of constructor\n * matching.\n */\npublic class MultiConstructor {\n\n    private final String first;\n\n    public MultiConstructor(String first, String second) {\n        this.first = first;\n    }\n\n    public MultiConstructor(String first) {\n        this.first = first;\n\n    }\n\n    public MultiConstructor(String first, Runnable something, boolean b) {\n        this.first = first;\n    }\n\n    public String getFirst() {\n        return this.first;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/NewFileExample.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.expectnew;\r\n\r\nimport java.io.File;\r\n\r\n/**\r\n * Used to demonstrate PowerMock's ability to mock new instance calls.\r\n */\r\npublic class NewFileExample {\r\n\r\n\tpublic boolean createDirectoryStructure(String directoryPath) {\r\n\t\tFile directory = new File(directoryPath);\r\n\r\n\t\tif (directory.exists()) {\r\n\t\t\tthrow new IllegalArgumentException(\"\\\"\" + directoryPath + \"\\\" already exists.\");\r\n\t\t}\r\n\r\n\t\treturn directory.mkdirs();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/PrimitiveAndWrapperDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.expectnew;\r\n\r\n/**\r\n * Used to demonstrate PowerMocks ability to deal with overloaded constructors\r\n * of primitive/wrapper types.\r\n */\r\npublic class PrimitiveAndWrapperDemo {\r\n\r\n\tprivate final int myInt;\r\n\r\n\tpublic PrimitiveAndWrapperDemo(int myInt) {\r\n\t\tthis.myInt = myInt;\r\n\t}\r\n\r\n\tpublic PrimitiveAndWrapperDemo(Integer myInt) {\r\n\t\tthis.myInt = myInt;\r\n\t}\r\n\r\n\tpublic int getMyInt() {\r\n\t\treturn myInt;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/PrimitiveAndWrapperUser.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.expectnew;\r\n\r\n/**\r\n * Used to demonstrate PowerMocks ability to deal with overloaded constructors\r\n * of primitive/wrapper types.\r\n */\r\npublic class PrimitiveAndWrapperUser {\r\n\r\n\tpublic int useThem() {\r\n\t\tPrimitiveAndWrapperDemo demo1 = new PrimitiveAndWrapperDemo(Integer.valueOf(42));\r\n\t\tPrimitiveAndWrapperDemo demo2 = new PrimitiveAndWrapperDemo(21);\r\n\t\treturn demo1.getMyInt() + demo2.getMyInt();\r\n\t}\r\n}"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/SimpleVarArgsConstructorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.expectnew;\n\npublic class SimpleVarArgsConstructorDemo {\n\n    private final byte[][] byteArrays;\n\n\n    public SimpleVarArgsConstructorDemo(byte[]... byteArrays) {\n        this.byteArrays = byteArrays;\n    }\n\n    public byte[][] getByteArrays() {\n        return byteArrays;\n    }\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/Target.java",
    "content": "package samples.expectnew;\n\n/**\n *\n */\npublic class Target implements ITarget{\n    private final String targetName;\n    private final int id;\n\n    public Target(String targetName, int id) {\n\n        this.targetName = targetName;\n        this.id = id;\n    }\n\n    @Override\n    public int getId() {\n        return id;\n    }\n\n    @Override\n    public String getName() {\n        return targetName;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectnew/VarArgsConstructorDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.expectnew;\r\n\r\nimport samples.Service;\r\n\r\npublic class VarArgsConstructorDemo {\r\n\r\n\tprivate final String[] strings;\r\n\tprivate final Service[] services;\r\n\tprivate final byte[][] byteArrays;\r\n    private final int[] ints;\r\n\r\n    public VarArgsConstructorDemo(String... strings) {\r\n\t\tthis.strings = strings;\r\n\t\tthis.services = new Service[0];\r\n\t\tthis.byteArrays = new byte[0][0];\r\n        this.ints = new int[0];\r\n\t}\r\n\r\n\tpublic VarArgsConstructorDemo(byte[]... byteArrays) {\r\n\t\tthis.byteArrays = byteArrays;\r\n\t\tthis.services = new Service[0];\r\n\t\tthis.strings = new String[0];\r\n        this.ints = new int[0];\r\n\t}\r\n\r\n\tpublic VarArgsConstructorDemo(Service... services) {\r\n\t\tthis.services = services;\r\n\t\tthis.strings = new String[0];\r\n\t\tthis.byteArrays = new byte[0][0];\r\n        this.ints = new int[0];\r\n\t}\r\n\r\n    public VarArgsConstructorDemo(float myFloat, int... ints) {\r\n        this.ints = ints;\r\n        this.services = new Service[0];\r\n\t\tstrings = new String[0];\r\n\t\tbyteArrays = new byte[0][0];\r\n\t}\r\n\r\n\tpublic String[] getAllMessages() {\r\n\t\treturn strings;\r\n\t}\r\n\r\n\tpublic Service[] getAllServices() {\r\n\t\treturn services;\r\n\t}\r\n\r\n\tpublic byte[][] getByteArrays() {\r\n\t\treturn byteArrays;\r\n\t}\r\n\r\n    public int[] getInts() {\r\n        return ints;\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/expectvoid/ExpectVoidDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.expectvoid;\n\npublic class ExpectVoidDemo {\n\n\tpublic void invokeAPrivateVoidMethod(int something) {\n\t\tprivateInvoke(something);\n\t}\n\n\tprivate void privateInvoke(int something) {\n\t\tSystem.out.println(\"Error in test privateInvoke in class \"\n\t\t\t\t+ ExpectVoidDemo.class.getSimpleName());\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/fieldmock/FieldInitializerDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.fieldmock;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class FieldInitializerDemo {\n\n\tprivate Map<Integer, String> map = new HashMap<Integer, String>();\n\n\tprivate static Map<Integer, String> staticMap = new HashMap<Integer, String>();\n\n\tprivate static Map<Integer, String> staticMap2;\n\tstatic {\n\t\tstaticMap2 = new HashMap<Integer, String>();\n\t\tSystem.out.println(\"### Static println!\");\n\t}\n\n\tpublic String getFromMap(int index) {\n\t\tSystem.out.println(\"getFromMap class = \" + map.getClass());\n\t\tSystem.out.println(\"staticMap = \" + staticMap);\n\t\tSystem.out.println(\"staticMap2 = \" + staticMap2);\n\t\treturn map.get(index);\n\t}\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/finalmocking/FinalDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.finalmocking;\n\nimport samples.simplemix.SimpleMix;\nimport samples.simplereturn.SimpleReturnExample;\n\npublic final class FinalDemo {\n\n\tpublic final String say(String string) {\n\t\treturn \"Hello \" + string;\n\t}\n\n\tpublic final void finalVoidCaller() {\n\t\tfinalVoidCallee();\n\t}\n\n\tpublic final void finalVoidCallee() {\n\t\tSystem.err.println(\"void method\");\n\t}\n\n\tpublic final native String sayFinalNative(String string);\n\n    public final SimpleReturnExample simpleReturnExample() {\n        return new SimpleReturnExample();\n    }\n\n    public final SimpleMix simpleMix() {\n        return new SimpleMix();\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/finalmocking/HoldingFinalDemo.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.finalmocking;\n\npublic final class HoldingFinalDemo {\n\n\tpublic FinalDemo getFinalDemo() {\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/finalmocking/StaticHoldingFinalDemo.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.finalmocking;\n\npublic class StaticHoldingFinalDemo {\n\n\tpublic static FinalDemo getFinalDemo() {\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/hashcode/HashCodeInitializedInCtor.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.hashcode;\n\nimport java.util.HashMap;\n\npublic class HashCodeInitializedInCtor {\n    private final HashMap<String, String> hash;\n\n    public HashCodeInitializedInCtor() {\n        hash = new HashMap<String, String>();\n    }\n\n    public static HashCodeInitializedInCtor newFaults() {\n        HashCodeInitializedInCtor fault = new HashCodeInitializedInCtor();\n        return fault;\n    }\n\n    @Override\n    public final int hashCode() {\n        return hash.hashCode();\n    }\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/injectmocks/DependencyHolder.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.injectmocks;\n\nimport samples.finalmocking.FinalDemo;\n\n/**\n * Simple class used to demonstrate setter injection..\n */\npublic class DependencyHolder {\n\n\tprivate FinalDemo finalDemo;\n\n\tpublic FinalDemo getFinalDemo() {\n\t\treturn finalDemo;\n\t}\n\n\tpublic void setFinalDemo(FinalDemo finalDemo) {\n\t\tthis.finalDemo = finalDemo;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/injectmocks/DependencyHolderQualifier.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage samples.injectmocks;\n\nimport samples.finalmocking.FinalDemo;\n\n/**\n * Simple class used to demonstrate setter injection..\n */\n@SuppressWarnings({\"WeakerAccess\", \"unused\"})\npublic class DependencyHolderQualifier {\n\n\tprivate FinalDemo finalDemo;\n\tprivate FinalDemo finalDemoQualifier;\n\n\tpublic FinalDemo getFinalDemo() {\n\t\treturn finalDemo;\n\t}\n\n\tpublic void setFinalDemo(FinalDemo finalDemo) {\n\t\tthis.finalDemo = finalDemo;\n\t}\n\n\tpublic FinalDemo getFinalDemoQualifier() {\n\t\treturn finalDemoQualifier;\n\t}\n\n\tpublic void setFinalDemoQualifier(FinalDemo finalDemoQualifier) {\n\t\tthis.finalDemoQualifier = finalDemoQualifier;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/injectmocks/InjectDemo.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.injectmocks;\n\n/**\n *\n */\n@SuppressWarnings({\"SameReturnValue\", \"unused\"})\npublic class InjectDemo {\n\n    @SuppressWarnings(\"unused\")\n    public String getMessage() {\n        return say(\"hello\");\n    }\n\n    @SuppressWarnings(\"UnusedParameters\")\n    private String say(String hello) {\n        return hello;\n    }\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/injectmocks/InjectDependencyHolder.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage samples.injectmocks;\n\n/**\n * Simple class used to demonstrate setter injection..\n */\n@SuppressWarnings(\"unused\")\npublic class InjectDependencyHolder {\n\n\tprivate InjectDemo injectDemo;\n\n    public InjectDemo getInjectDemo() {\n        return injectDemo;\n    }\n\n    public void setInjectDemo(InjectDemo injectDemo) {\n        this.injectDemo = injectDemo;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/injectmocks/InjectDependencyHolderQualifier.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\npackage samples.injectmocks;\n\n/**\n * Simple class used to demonstrate setter injection..\n */\n@SuppressWarnings(\"unused\")\npublic class InjectDependencyHolderQualifier {\n\n\tprivate InjectDemo injectDemo;\n    private InjectDemo injectDemoQualifier;\n\n    public InjectDemo getInjectDemo() {\n        return injectDemo;\n    }\n\n    public void setInjectDemo(InjectDemo injectDemo) {\n        this.injectDemo = injectDemo;\n    }\n\n    public InjectDemo getInjectDemoQualifier() {\n        return injectDemoQualifier;\n    }\n\n    public void setInjectDemoQualifier(InjectDemo injectDemoQualifier) {\n        this.injectDemoQualifier = injectDemoQualifier;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/innerclassmocking/ClassWithNonPrivateInnerClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.innerclassmocking;\n\n/**\n * Demonstrates the ability to mock an inner class (if the inner class is not\n * private).\n * \n * @author Johan Haleby\n */\npublic class ClassWithNonPrivateInnerClass {\n\n\tpublic String getMessage() {\n\t\treturn new InnerClass().getInnerMessage();\n\t}\n\n\tpublic class InnerClass {\n\t\tpublic String getInnerMessage() {\n\t\t\treturn \"A message from an inner class!\";\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/innerclassmocking/ClassWithPrivateInnerClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.innerclassmocking;\n\n/**\n * Used for demonstration of the ability to mock methods from a private inner\n * class. Due to limitations in Javassist (which doesn't seem to load inner\n * classes correctly??) we cannot mock private methods in inner classes. It\n * doesn't seem to have any effect when modifing the method modifier and setting\n * the method to public when loading the class by the mock class loader (but\n * why? Could be because the outer class has already been loaded?!).\n * \n */\npublic class ClassWithPrivateInnerClass {\n\tpublic String getMessage() {\n\t\treturn new InnerClass().getInnerMessage();\n\t}\n\n\tprivate class InnerClass {\n\t\tpublic String getInnerMessage() {\n\t\t\treturn \"A message from an inner class!\";\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/interfacefieldchange/InterfaceWithStaticFinalField.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.interfacefieldchange;\r\n\r\n/**\r\n * The purpose of the simple class is to demonstrate PowerMocks (possibly\r\n * future) ability to change static final fields in an interface. This is\r\n * normally not possible (the simple byte-code manipulation approach of removing\r\n * the final modifier doesn't work for interfaces since all static fields\r\n * <i>must</i> be final in interfaces according to the specification).\r\n */\r\npublic interface InterfaceWithStaticFinalField {\r\n\tstatic final String MY_STRING = \"My value\";\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsage.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.interfacemethodfinding;\n\nimport org.powermock.reflect.internal.WhiteboxImpl;\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\n\n/**\n * There was a bug in PowerMock 1.2 and its predecessors that made PowerMock\n * {@link WhiteboxImpl#getMethod(Class, Class...)} fail when invoking proxified\n * interface methods declared in extended interfaces. E.g. if interface A\n * extends B & C and a method was declared in B it wouldn't be found by\n * {@link WhiteboxImpl#getMethod(Class, Class...)} since it only used to\n * traverse the class hierarchy and not the structure of the extended\n * interfaces. This was fixed in version 1.3 and this class is used to\n * demonstrate the issue.\n * <p>\n * Thanks to Lokesh Vaddi for finding this bug and to provide an example.\n */\npublic class InterfaceMethodHierarchyUsage {\n\n\tpublic void usePreparedStatement() throws Exception {\n\t\tConnection conn = null;\n\t\t// PreparedStatement extends other interfaces, this is the point of\n\t\t// interest.\n\t\tPreparedStatement prepared = null;\n\t\ttry {\n\t\t\tconn = WsUtil.getConnection();\n\t\t\tprepared = conn.prepareStatement(\"select * from emp\");\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(e);\n\n\t\t} finally {\n\t\t\tconn.close();\n\t\t\tprepared.close();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/interfacemethodfinding/WsUtil.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.interfacemethodfinding;\n\nimport java.sql.Connection;\n\n/**\n * Dummy class that is used to setup expectations for the\n * {@link InterfaceMethodHierarchyUsage}.\n */\npublic class WsUtil {\n\n\tpublic static Connection getConnection() throws Exception {\n\n\t\tConnection conn = null;\n\n\t\treturn conn;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/java/ClassInsideJavaPackage.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.java;\n\npublic final class ClassInsideJavaPackage {\n    \n    public final String mockMe() {\n        return \"string\";\n    }\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/largemethod/MethodExceedingJvmLimit.java",
    "content": "/*\n *   Copyright 2016 the original author or authors.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\n */\n\npackage samples.largemethod;\n\n/**\n * Example of class with method which after instrumentation is larger than JVM limit.\n */\npublic class MethodExceedingJvmLimit {\n\n\t/**\n\t * Method size after instrumentation is equal to 91265.\n\t */\n\tpublic static String init() {\n\t\tString a = \"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\ta+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";a+=\"A\";\n\t\treturn a;\n\t}\n}"
  },
  {
    "path": "tests/utils/src/main/java/samples/methodhierarchy/MethodInvocationDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.methodhierarchy;\r\n\r\npublic class MethodInvocationDemo extends MethodInvocationDemoParent {\r\n\r\n\t@SuppressWarnings(\"unused\")\r\n\tprivate String getString() {\r\n\t\treturn getTheString();\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/methodhierarchy/MethodInvocationDemoGrandParent.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.methodhierarchy;\r\n\r\npublic class MethodInvocationDemoGrandParent {\r\n\r\n\tprotected String getTheString() {\r\n\t\treturn \"a string from MethodInvocationDemoGrandParent\";\r\n\t}\r\n\r\n\t@SuppressWarnings(\"unused\")\r\n\tprivate String getString() {\r\n\t\treturn \"MethodInvocationDemoGrandParent\";\r\n\t}\r\n\r\n\t@SuppressWarnings(\"unused\")\r\n\tprivate String getString(int index) {\r\n\t\treturn \"MethodInvocationDemoGrandParent: \" + index;\r\n\t}\r\n}"
  },
  {
    "path": "tests/utils/src/main/java/samples/methodhierarchy/MethodInvocationDemoParent.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.methodhierarchy;\r\n\r\npublic class MethodInvocationDemoParent extends MethodInvocationDemoGrandParent {\r\n\r\n\t@Override\r\n\tprotected String getTheString() {\r\n\t\treturn \"MethodInvocationDemoParent wrapped \" + super.getTheString();\r\n\t}\r\n\r\n\t@SuppressWarnings(\"unused\")\r\n\tprivate String getString() {\r\n\t\treturn \"MethodInvocationDemoParent\";\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/mockpolicy/ResultCalculator.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.mockpolicy;\r\n\r\npublic class ResultCalculator {\r\n\tprivate int operand;\r\n\r\n\tpublic ResultCalculator(int operand) {\r\n\t\tthis.operand = operand;\r\n\t}\r\n\r\n\tpublic double calculate() {\r\n\t\treturn Math.PI*operand;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/mockpolicy/SimpleClassWithADependency.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.mockpolicy;\r\n\r\n\r\npublic class SimpleClassWithADependency {\r\n\t\r\n\tprivate ResultCalculator calculator;\r\n\t\r\n\tpublic double getResult() {\r\n\t\treturn calculator.calculate();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/mockpolicy/SomeClassWithAMethod.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.mockpolicy;\r\n\r\npublic class SomeClassWithAMethod extends SomeClassWithAMethodParent {\r\n\r\n\t@Override\r\n\tpublic double getResult() {\r\n\t\treturn super.getResult() * 2;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/mockpolicy/SomeClassWithAMethodParent.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.mockpolicy;\r\n\r\npublic class SomeClassWithAMethodParent {\r\n\t\r\n\tpublic double getResult() {\r\n\t\treturn new ResultCalculator(4).calculate();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/mockpolicy/frameworkexample/NativeResult.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.mockpolicy.frameworkexample;\r\n\r\npublic class NativeResult {\r\n\t\r\n\tprivate final String result;\r\n\r\n\tpublic NativeResult(String result) {\r\n\t\tthis.result = result;\r\n\t}\r\n\t\r\n\tpublic String get() {\r\n\t\treturn result;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/mockpolicy/frameworkexample/SimpleFramework.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.mockpolicy.frameworkexample;\r\n\r\npublic class SimpleFramework {\r\n\t\r\n\tstatic {\r\n\t\tSystem.loadLibrary(\"framework.dll\");\r\n\t}\r\n\t\r\n\tpublic NativeResult doNativeStuff(String nativeStuffToDo) {\r\n\t\treturn new NativeResult(nativeStuffToDo);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/mockpolicy/frameworkexample/SimpleFrameworkUser.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.mockpolicy.frameworkexample;\r\n\r\npublic class SimpleFrameworkUser {\r\n\t\r\n\tpublic String performComplexOperation(String operation) {\r\n\t\treturn new SimpleFramework().doNativeStuff(operation).get();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/nativemocking/NativeMockingSample.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.nativemocking;\r\n\r\n/**\r\n * The purpose of this class is to invoke a native method in a collaborator.\r\n */\r\npublic class NativeMockingSample {\r\n\r\n\tprivate final NativeService nativeService;\r\n\r\n\tpublic NativeMockingSample(NativeService nativeService) {\r\n\t\tthis.nativeService = nativeService;\r\n\t}\r\n\r\n\tpublic String invokeNativeMethod(String param) {\r\n\t\treturn nativeService.invokeNative(param);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/nativemocking/NativeService.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.nativemocking;\r\n\r\n/**\r\n * The purpose of this class is to demonstrate that it's possible to mock native\r\n * methods using plain EasyMock class extensions.\r\n */\r\npublic class NativeService {\r\n\r\n\tpublic native String invokeNative(String nativeParameter);\r\n\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/newmocking/MyClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.newmocking;\n\npublic class MyClass {\n\n\tpublic String getMessage() {\n\t\treturn \"Hello world\";\n\t}\n\n\tpublic String getMessage(String message) {\n\t\treturn \"Hello world: \" + message;\n\t}\n\n\tpublic void voidMethod() {\n\t\tSystem.out.println(\"Void method!\");\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/newmocking/NewDemo.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.newmocking;\n\npublic final class NewDemo {\n\n    public void methodUnderTest()\n    {\n        SomeDependency loadingPool = new SomeDependency();\n        loadingPool.complete();\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/newmocking/SomeDependency.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.newmocking;\n\n\npublic class SomeDependency {\n    \n    private String thing=\"complete\";\n    \n    void complete()  {\n    \tSystem.out.println(thing.toString()); // PowerMockBugPartATest gives NPE here, PowerMockBugPartBTest works\n    }    \n}\n\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/newmocking/StupidNew.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.newmocking;\n\npublic class StupidNew {\n\n\tpublic String getMessage() {\n\t\tMyClass myClass = new MyClass();\n\t\treturn myClass.getMessage();\n\t}\n\n\tpublic String getMessageWithArgument() {\n\t\tMyClass myClass = new MyClass();\n\t\treturn myClass.getMessage(\"test\");\n\t}\n\n\tpublic void invokeVoidMethod() {\n\t\tMyClass myClass = new MyClass();\n\t\tmyClass.voidMethod();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/nice/NiceDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.nice;\r\n\r\npublic class NiceDemo {\r\n\r\n\tpublic void callAThenB() {\r\n\t\tA(\"String\");\r\n\t\tB(\"String 2\");\r\n\t}\r\n\r\n\tvoid A(String aString) {\r\n\t\t// Does nothing\r\n\t}\r\n\r\n\tvoid B(String aString) {\r\n\t\t// Does nothing\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/overloading/OverloadedMethodsExample.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.overloading;\n\nimport samples.classhierarchy.ChildA;\nimport samples.classhierarchy.Parent;\n\npublic class OverloadedMethodsExample {\n    public static void overloadedMethodWithOneArgument(Parent parent) {\n    }\n\n    public static void overloadedMethodWithOneArgument(ChildA child) {\n    }\n\n    public static void overloadedMethodWithTwoArguments(Parent parent, ChildA child) {\n    }\n\n    public static void overloadedMethodWithTwoArguments(Parent parent1, Parent parent2) {\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/overloading/OverloadingDemo.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.overloading;\n\nimport samples.classhierarchy.ChildA;\nimport samples.classhierarchy.Parent;\n\n/**\n * Demonstrates that PowerMock correctly invoke overloaded methods from the\n * MockGateway.\n */\npublic class OverloadingDemo {\n\n    public void performSingleOverloadedArgumentTest() {\n        Parent object = new ChildA();\n        OverloadedMethodsExample.overloadedMethodWithOneArgument(object);\n    }\n\n    public void performMethodOverloadTestWhenBothArgumentSame() {\n        Parent object1 = new ChildA();\n        Parent object2 = new ChildA();\n        OverloadedMethodsExample.overloadedMethodWithTwoArguments(object1, object2);\n    }\n\n    public void performMethodOverloadTestWithOneArgumentSameAndOneDiffernt() {\n        Parent object1 = new ChildA();\n        Parent object2 = new Parent();\n        OverloadedMethodsExample.overloadedMethodWithTwoArguments(object2, object1);\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/overloading/StaticAndInstanceMethodWithSameName.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.overloading;\n\nimport samples.classhierarchy.ChildA;\nimport samples.classhierarchy.Parent;\n\npublic class StaticAndInstanceMethodWithSameName {\n    public void overloaded(Parent parent) {\n    }\n\n    public static void overloaded(ChildA child) {\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/overloading/StaticAndInstanceMethodWithSameNameUser.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.overloading;\n\nimport samples.classhierarchy.ChildA;\nimport samples.classhierarchy.Parent;\n\n/**\n * Demonstrates that PowerMock correctly methods that seam to be overloaded but\n * differ because one is static and one is instance.\n */\npublic class StaticAndInstanceMethodWithSameNameUser {\n\n    public void performInstaceInvocation(StaticAndInstanceMethodWithSameName object) {\n        Parent child = new ChildA();\n        object.overloaded(child);\n    }\n\n    public void performStaticInvocation() {\n        Parent child = new ChildA();\n        StaticAndInstanceMethodWithSameName.overloaded((ChildA) child);\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/packageprivate/PackagePrivateClass.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.packageprivate;\r\n\r\n/**\r\n * This class demonstrates the ability for PowerMock to mock package private\r\n * classes. This is normally not an issue but since we've changed the CgLib\r\n * naming policy to allow for signed mocking PowerMock needs to byte-code\r\n * manipulate this class.\r\n */\r\nclass PackagePrivateClass {\r\n\r\n\tpublic int getValue() {\r\n\t\treturn returnAValue();\r\n\t}\r\n\r\n\tprivate int returnAValue() {\r\n\t\treturn 82;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/MockSelfDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.partialmocking;\n\nimport java.sql.Connection;\n\npublic class MockSelfDemo {\n\n    private int hello;\n\n    @SuppressWarnings(\"unused\")\n    private MockSelfDemo() {\n        hello = 42;\n    }\n\n    public MockSelfDemo(int hello) {\n        this.hello = hello;\n    }\n\n    public MockSelfDemo(Object string) {\n        this.hello = 4;\n    }\n\n    @Override\n    public int hashCode() {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + hello;\n        return result;\n    }\n\n    protected String establishConnection(Connection conn) throws Exception {\n        if (conn== null) {\n            return \"works\";\n        }  else {\n            return \"doesn't work\";\n        }\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj)\n            return true;\n        if (obj == null)\n            return false;\n        if (getClass() != obj.getClass())\n            return false;\n        final MockSelfDemo other = (MockSelfDemo) obj;\n        if (hello != other.hello)\n            return false;\n        return true;\n    }\n\n    public String aMethod() {\n        aMethod2();\n        return getString(\"world\");\n    }\n\n    public void aMethod2() {\n\n    }\n\n    public String getTwoStrings() {\n        return getString() + getString(\"world2\");\n    }\n\n    private String getString() {\n        return \"A String\";\n    }\n\n    public String getString(String string) {\n        return \"Hello \" + string;\n    }\n\n    public String getString2(String string) {\n        return \"Hello \" + string;\n    }\n\n    public String getString2() {\n        return \"Hello world\";\n    }\n\n    public int timesTwo(Integer anInt) {\n        return anInt * 2;\n    }\n\n    public int timesTwo(int anInt) {\n        return anInt * 2;\n    }\n\n    public int timesThree(int anInt) {\n        return anInt * 3;\n    }\n\n    public int getConstructorValue() {\n        return hello;\n    }\n\n    public static int getSomething() {\n        int retVal = methodToBeStubbed();\n        retVal = retVal * 2;\n        return retVal;\n    }\n\n    public static int methodToBeStubbed() {\n        return 6;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/MockSelfDemoSubClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.partialmocking;\n\npublic class MockSelfDemoSubClass {\n\n\tpublic String getAMessage() {\n\t\treturn \"A message\";\n\t}\n\n\tprotected String getAProtectedMessage() {\n\t\treturn \"protected\";\n\t}\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/MockSelfDemoWithSubClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.partialmocking;\n\npublic class MockSelfDemoWithSubClass extends MockSelfDemoSubClass {\n\n\tpublic String getMessage() {\n\t\treturn getInternalMessage() + getAMessage();\n\t}\n\n\tpublic String getSecondMessage() {\n\t\treturn getAProtectedMessage();\n\t}\n\n\tprivate String getInternalMessage() {\n\t\treturn \"Internal message\";\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/MockSelfWithNoDefaultConstructorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.partialmocking;\n\npublic class MockSelfWithNoDefaultConstructorDemo {\n\n\tprivate int hello;\n\n\tpublic MockSelfWithNoDefaultConstructorDemo(int hello) {\n\t\tthis.hello = hello;\n\t}\n\n\tpublic String aMethod() {\n\t\taMethod2();\n\t\treturn \"hello = \" + hello;\n\t}\n\n\tpublic void aMethod2() {\n\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/MockWithStaticStateDemo.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.partialmocking;\n\npublic class MockWithStaticStateDemo {\n\t\n\tprivate static final int state = 5;\n\n\tpublic static int getState() {\n\t\treturn state;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/PartialMockingExample.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.partialmocking;\r\n\r\n/**\r\n * Simple partial mocking example that should need no byte-code manipulation.\r\n */\r\npublic class PartialMockingExample {\r\n\r\n\tpublic String methodToTest() {\r\n\t\treturn methodToMock();\r\n\t}\r\n\r\n\tpublic String methodToMock() {\r\n\t\tSystem.out.println(\"If you see this the test is failing!\");\r\n\t\treturn \"REAL VALUE\";\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/PartialMockingWithConstructor.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.partialmocking;\r\n\r\npublic class PartialMockingWithConstructor {\r\n\tpublic PartialMockingWithConstructor() {\r\n\t\tinitialize();\r\n\t}\r\n\r\n\tpublic void initialize() {\r\n\t}\r\n\r\n\tpublic void touch() {\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/partialmocking/PrivatePartialMockingExample.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.partialmocking;\r\n\r\n/**\r\n * Simple partial mocking example that should need no byte-code manipulation.\r\n */\r\npublic final class PrivatePartialMockingExample {\r\n\r\n    public String methodToTest() {\r\n        return methodToMock(\"input\");\r\n    }\r\n\r\n    private String methodToMock(String input) {\r\n        return \"REAL VALUE = \" + input;\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/powermockignore/PowerMockIgnoreDemo.java",
    "content": "package samples.powermockignore;\r\n\r\nimport javax.swing.*;\r\n\r\npublic class PowerMockIgnoreDemo {\r\n\r\n\tpublic void showDialog() {\r\n\t\tJOptionPane.showInputDialog(\"Input:\");\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/privateandfinal/PrivateFinal.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.privateandfinal;\n\n/**\n * A class used to test the functionality to mock private methods that are also\n * final.\n * \n * @author Johan Haleby\n */\npublic class PrivateFinal {\n\tpublic String say(String name) {\n\t\treturn sayIt(name);\n\t}\n\n\tprivate final String sayIt(String name) {\n\t\treturn \"Hello \" + name;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/privateandfinal/PrivateFinalOverload.java",
    "content": "/*\n * Copyright 2014 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.privateandfinal;\n\n/**\n * A class used to test the functionality of capturing arguments when methods are overloaded and private and final.\n *\n * @author Johan Haleby\n */\npublic class PrivateFinalOverload {\n    public String say(String name) {\n        return say(\"Hello\", name);\n    }\n\n    private final String say(String prefix, String name) {\n        return prefix + \" \" + name;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/privatefield/MockSelfPrivateFieldServiceClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.privatefield;\n\nimport samples.Service;\n\n/**\n * A class that uses a private Service field and no setter. This is approach is\n * common in DI frameworks like Guice and Wicket IoC.\n * \n * @author Johan Haleby\n */\npublic class MockSelfPrivateFieldServiceClass {\n\tprivate Service service;\n\n\tpublic String getCompositeMessage() {\n\t\tfinal String message = getOwnMessage() + service.getServiceMessage();\n\t\treturn message;\n\t}\n\n\tprivate String getOwnMessage() {\n\t\treturn \"My message\";\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/privatefield/SimplePrivateFieldServiceClass.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.privatefield;\n\nimport samples.Service;\n\n/**\n * A class that uses a private Service field and no setter. This is approach is\n * common in DI frameworks like Guice and Wicket IoC.\n * \n * @author Johan Haleby\n */\npublic class SimplePrivateFieldServiceClass {\n\tprivate Service service;\n\n\tpublic String useService() {\n\t\treturn service.getServiceMessage();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/privatemocking/PrivateMethodDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.privatemocking;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.Reader;\n\n/**\n * A class used to test the functionality to mock private methods.\n *\n * @author Johan Haleby\n */\npublic class PrivateMethodDemo {\n    public String say(String name) {\n        return sayIt(name);\n    }\n\n    public String enhancedSay(String firstName, String lastName) {\n        return sayIt(firstName, \" \", lastName);\n    }\n\n    public String sayYear(String name, int years) {\n        return doSayYear(years, name);\n    }\n\n    private String doSayYear(int years, String name) {\n        return \"Hello \" + name + \", you are \" + years + \" old.\";\n    }\n\n    private String sayIt(String firstName, String spacing, String lastName) {\n        return \"Hello\" + firstName + spacing + lastName;\n    }\n\n    private String sayIt(String name) {\n        return \"Hello \" + name;\n    }\n\n    @SuppressWarnings(\"unused\")\n    private String sayIt() {\n        return \"Hello world\";\n    }\n\n    public int methodCallingPrimitiveTestMethod() {\n        return aTestMethod(10);\n    }\n\n    public int methodCallingWrappedTestMethod() {\n        return aTestMethod(new Integer(15));\n    }\n\n    private int aTestMethod(int aValue) {\n        return aValue;\n    }\n\n    private Integer aTestMethod(Integer aValue) {\n        return aValue;\n    }\n\n    public void doArrayStuff(String v) {\n        doArrayInternal(new String[]{v});\n    }\n\n    private void doArrayInternal(String[] strings) {\n    }\n\n    public void doObjectStuff(Object o) {\n        doObjectInternal(o);\n    }\n\n    private void doObjectInternal(Object o) {\n    }\n\n    public int invokeVarArgsMethod(int a, int b) {\n        return varArgsMethod(a, b);\n    }\n\n    private int varArgsMethod(int... ints) {\n        int sum = 0;\n        for (int i : ints) {\n            sum += i;\n        }\n        return sum;\n    }\n\n    private Reader createReader(File folder) throws FileNotFoundException {\n        return null;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/reflection/ReflectionInstantiator.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.reflection;\n\npublic class ReflectionInstantiator {\n\n\tpublic boolean instantiateUseMe() throws ClassNotFoundException {\n\t\tClass<?> reflectionClass = Class.forName(\n\t\t\t\t\"samples.reflection.UseMeInterface\", true, Thread\n\t\t\t\t\t\t.currentThread().getContextClassLoader());\n\t\treturn reflectionClass.isAssignableFrom(UseMe.class);\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/reflection/UseMe.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.reflection;\n\npublic class UseMe implements UseMeInterface {\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/reflection/UseMeInterface.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.reflection;\n\npublic interface UseMeInterface {\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/rule/SimpleThing.java",
    "content": "/*\r\n * Copyright 2011 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\npackage samples.rule;\r\n\r\npublic interface SimpleThing {\r\n    String getThingName();\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/rule/SimpleThingCreator.java",
    "content": "/*\r\n * Copyright 2011 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\npackage samples.rule;\r\n\r\npublic class SimpleThingCreator {\r\n\r\n    public static SimpleThing createSimpleThing() {\r\n        return new SimpleThingImpl();\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/rule/SimpleThingImpl.java",
    "content": "/*\r\n * Copyright 2011 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\npackage samples.rule;\r\n\r\npublic class SimpleThingImpl implements SimpleThing {\r\n\r\n    @Override\r\n    public String getThingName() {\r\n        return null;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/rule/ThingToTest.java",
    "content": "/*\r\n * Copyright 2011 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\npackage samples.rule;\r\n\r\npublic class ThingToTest {\r\n    private final SimpleThing simpleThing;\r\n\r\n    public ThingToTest() {\r\n        simpleThing = SimpleThingCreator.createSimpleThing();\r\n    }\r\n\r\n    public String getName() {\r\n        // uncomment the line below and the test passes\r\n        //        return simpleThing.getThingName();\r\n        return \"Smith\";\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/servletmocking/SampleServlet.java",
    "content": "/*\r\n * Copyright 2010 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\npackage samples.servletmocking;\r\n\r\nimport javax.servlet.ServletException;\r\nimport javax.servlet.http.HttpServlet;\r\nimport javax.servlet.http.HttpServletRequest;\r\nimport javax.servlet.http.HttpServletResponse;\r\nimport java.io.IOException;\r\n\r\n/**\r\n * @author volodymyr.tsukur\r\n */\r\npublic class SampleServlet extends HttpServlet {\r\n\r\n    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\r\n        response.getWriter().write(\"out\");\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/simplemix/SimpleMix.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.simplemix;\r\n\r\n/**\r\n * This class is used to demonstrate features such as static, final and partial\r\n * mocking as well as access internal state.\r\n */\r\npublic class SimpleMix {\r\n\r\n    private SimpleMixCollaborator collaborator;\r\n\r\n    public final int calculate() {\r\n        return (SimpleMixUtilities.getRandomInteger() + getValue() - collaborator.getRandomInteger()) * new SimpleMixConstruction().getMyValue();\r\n    }\r\n\r\n    private int getValue() {\r\n        return (int) (System.currentTimeMillis() / 1000);\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/simplemix/SimpleMixCollaborator.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.simplemix;\r\n\r\nimport java.util.Random;\r\n\r\npublic final class SimpleMixCollaborator {\r\n\r\n\tpublic final int getRandomInteger() {\r\n\t\treturn new Random().nextInt(400);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/simplemix/SimpleMixConstruction.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.simplemix;\n\npublic class SimpleMixConstruction {\n\n    public int getMyValue() {\n        return 4;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/simplemix/SimpleMixUtilities.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.simplemix;\r\n\r\nimport java.util.Random;\r\n\r\npublic class SimpleMixUtilities {\r\n\tpublic static int getRandomInteger() {\r\n\t\treturn new Random().nextInt();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/simplereturn/SimpleReturnExample.java",
    "content": "package samples.simplereturn;\r\n\r\npublic class SimpleReturnExample {\r\n\r\n\tpublic int mySimpleMethod() {\r\n\t\treturn 44;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/simplereturn/SimpleReturnExampleUser.java",
    "content": "package samples.simplereturn;\r\n\r\npublic class SimpleReturnExampleUser {\r\n\r\n\tprivate SimpleReturnExample simpleReturnExample;\r\n\r\n\tpublic SimpleReturnExampleUser(SimpleReturnExample intReturn2) {\r\n\t\tsuper();\r\n\t\tthis.simpleReturnExample = intReturn2;\r\n\t}\r\n\r\n\tpublic int myMethod() {\r\n\t\treturn simpleReturnExample.mySimpleMethod();\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/singleton/SimpleStaticService.java",
    "content": "package samples.singleton;\n\npublic class SimpleStaticService {\n\n    public static String say(final String string) {\n        return \"Hello \" + string;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/singleton/StaticExample.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.singleton;\n\n/**\n *Can be used to assert that partial mocking of static methods works.\n */\npublic class StaticExample {\n\n\tpublic static void voidMethod() {\n\t\tprivateVoidMethod();\n\t}\n\n\tprivate static void privateVoidMethod() {\n\t}\n\n\tpublic static void voidFinalMethod() {\n\t\tprivateVoidFinalMethod();\n\t}\n\n\tprivate static final void privateVoidFinalMethod() {\n\t}\n\t\n\tpublic static void staticVoidMethod() {\n\t    throw new IllegalArgumentException(\"This should never happen\");\n    }\n\t\n\tpublic static String staticMethodReturningString() {\n        throw new IllegalArgumentException(\"This should never happen\");\n    }\n\t\n\tpublic static final void staticFinalVoidMethod() {\n        throw new IllegalArgumentException(\"This should never happen\");\n    }\n\n\tpublic static Object objectMethod() {\n\t\treturn privateObjectMethod();\n\t}\n\n\tprivate static Object privateObjectMethod() {\n\t\treturn new Object();\n\t}\n\n\tpublic static Object objectFinalMethod() {\n\t\treturn privateObjectFinalMethod();\n\t}\n\n\tprivate static final Object privateObjectFinalMethod() {\n\t\treturn new Object();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/singleton/StaticHelper.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.singleton;\n\npublic class StaticHelper {\n\n\tpublic static void sayHelloHelper() {\n\t\tSystem.out.println(\"hello\");\n\t}\n\n\tpublic static void sayHelloAgain() {\n\t\tSystem.out.println(\"hello\");\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/singleton/StaticService.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.singleton;\n\nimport java.util.concurrent.Callable;\n\n/**\n * Test class to demonstrate static, static+final, static+native and\n * static+final+native methods mocking.\n * \n * @author Johan Haleby\n * @author Jan Kronquist\n */\npublic class StaticService {\n\n\tprivate static int number = 17;\n    private static Integer intValue;\n    public static String messageStorage;\n\n    private int secret = 23;\n\n    public static void sayHello(String message) {\n        messageStorage = message;\n    }\n\n    public static void sayHello(Integer intValue) {\n        StaticService.intValue = intValue;\n    }\n\n\tpublic static int getNumberFromInner() {\n\t\treturn new Callable<Integer>() {\n\t\t\t@Override\n\t\t\tpublic Integer call() {\n\t\t\t\treturn number;\n\t\t\t}\n\t\t}.call();\n\t}\n\n\tpublic static int getNumberFromInnerInstance() {\n\t\treturn new StaticService().internalGetNumberFromInnerInstance();\n\t}\n\n\tpublic int internalGetNumberFromInnerInstance() {\n\t\treturn new Callable<Integer>() {\n\t\t\t@Override\n\t\t\tpublic Integer call() {\n\t\t\t\treturn secret;\n\t\t\t}\n\t\t}.call();\n\t}\n\n\tpublic static String doStatic(int i) {\n\t\tthrow new UnsupportedOperationException(\"method not implemented yet...\");\n\t}\n\n\tpublic static void assertThatVerifyWorksForMultipleMocks() {\n\t\tStaticService.sayHello();\n\t\tStaticHelper.sayHelloHelper();\n\t}\n\n\tpublic static void sayHello() {\n\t\tStaticHelper.sayHelloHelper();\n\t\tStaticHelper.sayHelloHelper();\n\t}\n\n\tpublic static void sayHelloAgain() {\n\t\tStaticHelper.sayHelloAgain();\n\t\tStaticHelper.sayHelloAgain();\n\t}\n\t\n\tpublic static void throwException(){\n        throw new RuntimeException(\"How are you?\");\n    }\n\n\tpublic static String say(String string) {\n\t\treturn \"Hello \" + string;\n\t}\n\n\tpublic final static String sayFinal(String string) {\n\t\treturn \"Hello \" + string;\n\t}\n\n\tpublic native static String sayNative(String string);\n\n\tpublic final native static String sayFinalNative(String string);\n\n\tpublic static int calculate(int a, int b) {\n\t\treturn a + b;\n\t}\n\n\tprivate static String sayPrivateStatic(String string) {\n\t\treturn \"Hello private static \" + string;\n\t}\n\n\tprivate static String sayPrivateFinalStatic(String string) {\n\t\treturn \"Hello private static \" + string;\n\t}\n\n\tprivate static final native String sayPrivateNativeFinalStatic(String string);\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/singleton/StaticWithPrivateCtor.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.singleton;\n\npublic class StaticWithPrivateCtor {\n\n    private StaticWithPrivateCtor(){\n    }\n\n    public static String staticMethod() {\n        return \"something\";\n    }\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/spy/SpyObject.java",
    "content": "/*\n * Copyright 2013 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.spy;\n\npublic class SpyObject {\n\n    public String getMyString() {\n        return \"something\";\n    }\n\n    public String getStringTwo() {\n        return \"two\";\n    }\n\n\n    public void throwException() {\n        throw new RuntimeException(\"Aaaaa! Test is failed.\");\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.staticandinstance;\n\n/**\n * Demonstrates how to mock both instance and static methods in the same test\n *\n * @author Johan Haleby\n */\npublic class StaticAndInstanceDemo {\n\n    public String getMessage() {\n        return getPrivateMessage() + StaticAndInstanceDemo.getStaticMessage();\n    }\n\n    private String getPrivateMessage() {\n        return \"Private \";\n    }\n\n    public static final String getStaticMessage() {\n        return \"hello world!\";\n    }\n\n    public static void aVoidMethod() {\n    }\n\n    public static Object aMethod2(String aString) {\n        return null;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceWithConstructorCodeDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.staticandinstance;\n\n/**\n * The purpose of this class is to be used to verify that the\n * http://code.google.com/p/powermock/issues/detail?id=4 is fixed.\n * \n */\npublic class StaticAndInstanceWithConstructorCodeDemo {\n\n\tprivate final StaticAndInstanceDemo staticAndInstanceDemo;\n\n\tpublic StaticAndInstanceWithConstructorCodeDemo(\n\t\t\tStaticAndInstanceDemo staticAndInstanceDemo) {\n\t\tthis.staticAndInstanceDemo = staticAndInstanceDemo;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn StaticAndInstanceDemo.getStaticMessage()\n\t\t\t\t+ staticAndInstanceDemo.getMessage();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/staticinitializer/AbstractStaticInitializerExample.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.staticinitializer;\n\npublic abstract class AbstractStaticInitializerExample {\n\n\n    static {\n        if (true) {\n            throw new RuntimeException(\"This code must be suppressed!\");\n        }\n    }\n\n    public static String getStaticString() {\n        return \"something\";\n    }\n\n    public String getString() {\n        return \"something\";\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/staticinitializer/EvilStaticInitializerExample.java",
    "content": "/*\r\n * Copyright 2009 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.staticinitializer;\r\n\r\n/**\r\n * Simple example of a class with a static initializer.\r\n */\r\npublic class EvilStaticInitializerExample {\r\n\r\n\tpublic static final String FAILED_TO_LOAD_LIBRARY_MESSAGE = \"Failed to load a required dll, please make sure that you've installed the software correctly\";\r\n\r\n\tstatic {\r\n\t\ttry {\r\n\t\t\tSystem.loadLibrary(\"path/to/mylibrary.dll\");\r\n\t\t} catch (UnsatisfiedLinkError error) {\r\n\t\t\tthrow new UnsatisfiedLinkError(FAILED_TO_LOAD_LIBRARY_MESSAGE);\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t * We imagine that this method require the library to execute, but we want\r\n\t * to test it anyway in separation.\r\n\t */\r\n\tpublic String doSomeNativeStuffUsingTheLoadedSystemLibrary() {\r\n\t\treturn \"native stuff\";\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/staticinitializer/InterfaceComputation.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.staticinitializer;\n\ninterface InterfaceA\n{\n    public static final int A = 2 * InterfaceB.B;\n//    public void methodA();\n} // End of interface\ninterface InterfaceB\n{\n    public static final int B = InterfaceC.C + 1;\n//    public String methodB(int qwe);\n} // End of interface\ninterface InterfaceC extends InterfaceA\n{\n    public static final int C = A + 1;\n} // End of interface\n\npublic class InterfaceComputation implements InterfaceA, InterfaceB, InterfaceC\n{\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(calculateWithinHierarchy());\n\t}\n\tpublic static int calculateWithinHierarchy() {\n\t\treturn C + B + A;\n\t}\n\tpublic static int calculateWithReference() {\n\t\treturn InterfaceC.C + InterfaceB.B + InterfaceA.A;\n\t}\n\n//\tpublic void methodA() {\n//\t}\n//\n//\tpublic String methodB(int qwe) {\n//\t\treturn \"\";\n//\t} \n} // End of class\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/staticinitializer/SimpleStaticInitializerExample.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.staticinitializer;\n\npublic class SimpleStaticInitializerExample {\n\n\tprivate static final String string;\n\n\tstatic {\n\t\tstring = \"static world!\";\n\t}\n\n\tpublic String getString() {\n\t\treturn string;\n\t}\n\n\tpublic final String getConcatenatedString(String concat) {\n\t\treturn concat + \" \" + string;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/staticinitializer/StaticInitializerExample.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.staticinitializer;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class StaticInitializerExample {\n\n    private static final Set<String> mySet;\n\n    static {\n        mySet = new HashSet<String>();\n        if (true) {\n            throw new RuntimeException(\"This code must be suppressed!\");\n        }\n    }\n\n    public static Set<String> getMySet() {\n        return mySet;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/stress/ClassWithStatic.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.stress;\n\npublic class ClassWithStatic {\n\n    public static String a(){\n        return \"str\";\n    }\n    public static String b(){\n        return \"str\";\n    }\n    public static String c(){\n        return \"str\";\n    }\n    public static String d(){\n        return \"str\";\n    }\n    public static String e(){\n        return \"str\";\n    }\n    public static String f(){\n        return \"str\";\n    }\n    public static String g(){\n        return \"str\";\n    }\n    public static String h(){\n        return \"str\";\n    }\n}"
  },
  {
    "path": "tests/utils/src/main/java/samples/stress/StressSample.java",
    "content": "/*\n * Copyright 2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage samples.stress;\n\npublic class StressSample {\n\tpublic String a1(){\n\t\treturn ClassWithStatic.a();\n\t}\n\tpublic String b1(){\n\t\treturn ClassWithStatic.b();\n\t}\n\tpublic String c1(){\n\t\treturn ClassWithStatic.c();\n\t}\n\tpublic String d1(){\n\t\treturn ClassWithStatic.d();\n\t}\n\tpublic String e1(){\n\t\treturn ClassWithStatic.e();\n\t}\n\tpublic String f1(){\n\t\treturn ClassWithStatic.f();\n\t}\n\tpublic String g1(){\n\t\treturn ClassWithStatic.g();\n\t}\n\tpublic String h1(){\n\t\treturn ClassWithStatic.h();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/strict/StrictDemo.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.strict;\r\n\r\npublic class StrictDemo {\r\n\r\n\tpublic void callAThenB() {\r\n\t\tA();\r\n\t\tB();\r\n\t}\r\n\r\n\tprivate void A() {\r\n\t\t// Does nothing\r\n\t}\r\n\r\n\tprivate void B() {\r\n\t\t// Does nothing\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/AppaleList.java",
    "content": "/*\r\n * Copyright 2010 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\npackage samples.suppressconstructor;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\npublic class AppaleList {\r\n\t\t\r\n\tpublic AppaleList() {\r\n        throw new IllegalArgumentException(\"Shouldn't be called\");\r\n\t}\r\n\r\n\tpublic AppaleList(String str) {\r\n        throw new IllegalArgumentException(\"Shouldn't be called\");\r\n\t}\r\n\r\n\tpublic String getAll() {\r\n\t\tList<String> list = new ArrayList<String>();\r\n\t\tlist.add(\"sb1\");\r\n\t\tList<String> list1 = new ArrayList<String>(10);\r\n\t\tlist1.add(\"sb2\");\r\n\t\tlist1.add(\"sb3\");\r\n\t\tlist1.add(\"sb4\");\r\n\t\treturn \"str\";\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/InvokeConstructor.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class InvokeConstructor {\n\n\tpublic String doStuff(String m) {\n\t\treturn new SuppressConstructorHierarchy(m).getMessage();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class SuppressConstructorDemo extends\n\t\tSuppressConstructorSubclassDemo {\n\n\tpublic SuppressConstructorDemo(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic String getMyOwnMessage() {\n\t\treturn returnAMessage();\n\t}\n\n\tprivate String returnAMessage() {\n\t\treturn \"my message\";\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorHeirarchyEvilGrandParent.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class SuppressConstructorHeirarchyEvilGrandParent {\n\n\tSuppressConstructorHeirarchyEvilGrandParent() {\n\t\tthrow new RuntimeException(\"This should be suppressed!!\");\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorHierarchy.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class SuppressConstructorHierarchy extends SuppressConstructorHierarchyParent {\n\n\tpublic SuppressConstructorHierarchy(String message) {\n\t\tsuper(message);\n\t}\n\n\t/**\n\t * This method is just here to check if it works to execute several tests\n\t * with the same test suite class loader.\n\t * \n\t * @return 42.\n\t */\n\tpublic int getNumber() {\n\t\treturn 42;\n\t}\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorHierarchyParent.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class SuppressConstructorHierarchyParent extends\n\t\tSuppressConstructorHeirarchyEvilGrandParent {\n\n\tprivate String message;\n\n\tSuppressConstructorHierarchyParent() {\n\t\tSystem.out.println(\"Parent constructor\");\n\t\tthis.message = \"Default message\";\n\t}\n\n\tSuppressConstructorHierarchyParent(String message) {\n\t\tSystem.out.println(\"Parent constructor with message\");\n\t\tthis.message = message;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorSubclassDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class SuppressConstructorSubclassDemo {\n\n\tprivate String message;\n\n\tSuppressConstructorSubclassDemo(String message) {\n\t\tthis.message = message;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/SuppressNonParentConstructorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class SuppressNonParentConstructorDemo {\n\n\tpublic SuppressNonParentConstructorDemo(String message) {\n\t\tthrow new IllegalStateException(message);\n\t}\n\n\tpublic String getHello() {\n\t\treturn \"Hello\";\n\t}\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressconstructor/SuppressSpecificConstructorDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressconstructor;\n\npublic class SuppressSpecificConstructorDemo {\n\n\tpublic SuppressSpecificConstructorDemo() {\n\t\tthrow new IllegalStateException(\n\t\t\t\t\"This constructor should not be suppress\");\n\t}\n\n\tpublic SuppressSpecificConstructorDemo(String message) {\n\t\tthrow new IllegalStateException(message);\n\t}\n\t\n\tpublic String getHello() {\n\t\treturn \"Hello\";\n\t}\n\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppresseverything/SuppressEverything.java",
    "content": "/*\n * Copyright 2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppresseverything;\n\npublic class SuppressEverything {\n\n    public SuppressEverything() {\n        throw new IllegalStateException(\"error\");\n    }\n\n    public SuppressEverything(String string) {\n        throw new IllegalStateException(\"error\");\n    }\n\n    public int something() {\n        throw new IllegalStateException(\"error\");\n    }\n\n    public void somethingElse() {\n        throw new IllegalStateException(\"error\");\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressfield/DomainObject.java",
    "content": "package samples.suppressfield;\r\n\r\npublic class DomainObject {\r\n\r\n\tpublic DomainObject() {\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressfield/ItemRepository.java",
    "content": "package samples.suppressfield;\n\nimport java.util.HashMap;\n\npublic class ItemRepository {\n    private static HashMap<String, String> itemMap = new HashMap<String, String>();\n\n    @SuppressWarnings(\"unused\")\n    private MyClass myClass = new MyClass();\n\n    private int totalItems = 0;\n\n    public void addItem(String key, String value) {\n        itemMap.put(key, value);\n        totalItems++;\n    }\n\n    public void delItem(String key) {\n        if (itemMap.containsKey(key)) {\n            itemMap.remove(key);\n            totalItems--;\n        }\n    }\n\n    private static class MyClass {\n        public MyClass() {\n            throw new IllegalArgumentException(\"Constructor should never be called during this test\");\n        }\n    }\n}"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressfield/SuppressField.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.suppressfield;\r\n\r\npublic class SuppressField {\r\n\r\n\tprivate static final int MY_VALUE = 8;\r\n\r\n\tprivate static final Object MY_OBJECT = new Object();\r\n\r\n\tprivate final boolean myBoolean = true;\r\n\r\n\tprivate final Boolean myWrappedBoolean = Boolean.TRUE;\r\n\r\n\tprivate final Object mySecondValue = new Object();\r\n\r\n\tprivate DomainObject domainObject = new DomainObject();\r\n\r\n\tpublic Object getMySecondValue() {\r\n\t\treturn mySecondValue;\r\n\t}\r\n\r\n\tpublic DomainObject getDomainObject() {\r\n\t\treturn domainObject;\r\n\t}\r\n\r\n\tprivate char myChar = 'a';\r\n\r\n\tpublic static int getMyValue() {\r\n\t\treturn MY_VALUE;\r\n\t}\r\n\r\n\tpublic static Object getMyObject() {\r\n\t\treturn MY_OBJECT;\r\n\t}\r\n\r\n\tpublic boolean isMyBoolean() {\r\n\t\treturn myBoolean;\r\n\t}\r\n\r\n\tpublic Boolean getMyWrappedBoolean() {\r\n\t\treturn myWrappedBoolean;\r\n\t}\r\n\r\n\tpublic char getMyChar() {\r\n\t\treturn myChar;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressmethod/SuppressMethod.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressmethod;\n\npublic class SuppressMethod extends SuppressMethodParent {\n\n    public static final Object OBJECT = new Object();\n\n    public Object getObjectWithArgument(String argument) {\n        return OBJECT;\n    }\n\n    public Object getObject() {\n        return OBJECT;\n    }\n\n    public static Object getObjectStatic() {\n        return OBJECT;\n    }\n\n    public byte getByte() {\n        return Byte.MAX_VALUE;\n    }\n\n    public short getShort() {\n        return Short.MAX_VALUE;\n    }\n\n    public int getInt() {\n        return Integer.MAX_VALUE;\n    }\n\n    public long getLong() {\n        return Long.MAX_VALUE;\n    }\n\n    public boolean getBoolean() {\n        return true;\n    }\n\n    public float getFloat() {\n        return Float.MAX_VALUE;\n    }\n\n    public double getDouble() {\n        return Double.MAX_VALUE;\n    }\n\n    public double getDouble(double value) {\n        return value;\n    }\n\n    public void invokeVoid(StringBuilder s) {\n        s.append(\"This should be suppressed!\");\n    }\n\n    @Override\n    public int myMethod() {\n        return 20 + super.myMethod();\n    }\n\n    public Object sameName(int i) {\n        return OBJECT;\n    }\n\n    public Object sameName(float f) {\n        return OBJECT;\n    }\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressmethod/SuppressMethodExample.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.suppressmethod;\n\npublic class SuppressMethodExample extends SuppressMethodParent {\n\n\tpublic static final Object OBJECT = new Object();\n\n\tpublic Object getObject() {\n\t\treturn OBJECT;\n\t}\n\n\tpublic Object getStringObject() {\n\t\treturn \"test\";\n\t}\n\n\tpublic static Object getStringObjectStatic() {\n\t\treturn \"test\";\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/suppressmethod/SuppressMethodParent.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\npackage samples.suppressmethod;\r\n\r\npublic abstract class SuppressMethodParent {\r\n\t\r\n\tpublic int myMethod() {\r\n\t\treturn 42;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/swing/ReallySimpleSwingDemo.java",
    "content": "package samples.swing;\r\n\r\nimport javax.swing.*;\r\n\r\npublic class ReallySimpleSwingDemo {\r\n\r\n\tpublic void displayMessage(String message) {\r\n\t\tJOptionPane.showMessageDialog(null, message);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/swing/SimpleSwingDemo.java",
    "content": "/*\n * Copyright 2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.swing;\n\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\n/**\n * A basic swing application example.\n * \n * @author Johan Haleby\n */\npublic class SimpleSwingDemo extends JFrame {\n\n\tprivate static final long serialVersionUID = -190175253588111657L;\n\n\tpublic SimpleSwingDemo() {\n\t\tinitialize();\n\t}\n\n\tprivate void initialize() {\n\t\tsetLayout(new FlowLayout());\n\t\tfinal JLabel jlbHelloWorld = new JLabel(\"Hello World!\");\n\t\tJButton jButton = new JButton(\"Click Me!\");\n\n\t\tjButton.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent actionevent) {\n\t\t\t\tjlbHelloWorld.setText(\"Clicked on button\");\n\t\t\t}\n\t\t});\n\n\t\tadd(jlbHelloWorld);\n\t\tadd(jButton);\n\t\tsetSize(100, 100);\n\t\tsetVisible(true);\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew SimpleSwingDemo();\n\t}\n}\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/system/SystemClassUser.java",
    "content": "/*\r\n * Copyright 2008 the original author or authors.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage samples.system;\r\n\r\nimport java.io.IOException;\r\nimport java.io.UnsupportedEncodingException;\r\nimport java.net.*;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\nimport java.util.UUID;\r\n\r\n/**\r\n * Class used to demonstrate PowerMock's ability to mock system classes.\r\n */\r\npublic class SystemClassUser {\r\n\r\n    public void threadSleep() throws InterruptedException {\r\n        Thread.sleep(5000);\r\n    }\r\n\r\n    public String performEncode() throws UnsupportedEncodingException {\r\n        return URLEncoder.encode(\"string\", \"enc\");\r\n    }\r\n\r\n    public Process executeCommand() throws IOException {\r\n        return Runtime.getRuntime().exec(\"command\");\r\n    }\r\n\r\n    public String getSystemProperty() throws IOException {\r\n        return System.getProperty(\"property\");\r\n    }\r\n\r\n    public void doMoreComplicatedStuff() throws IOException {\r\n        System.setProperty(\"nanoTime\", Long.toString(System.nanoTime()));\r\n    }\r\n\r\n    public void copyProperty(String to, String from) throws IOException {\r\n        System.setProperty(to, System.getProperty(from));\r\n    }\r\n\r\n    public String format(String one, String args) throws IOException {\r\n        return String.format(one, args);\r\n    }\r\n\r\n    public URL newURL(String anUrl) throws MalformedURLException {\r\n        return new URL(anUrl);\r\n    }\r\n\r\n    public StringBuilder newStringBuilder() {\r\n        return new StringBuilder();\r\n    }\r\n\r\n    public void shuffleCollection(List<?> list) {\r\n        Collections.shuffle(list);\r\n    }\r\n\r\n    public URLConnection useURL(URL url) throws IOException {\r\n        return url.openConnection();\r\n    }\r\n     \r\n    public InetAddress getLocalHost() throws IOException {\r\n        return InetAddress.getLocalHost();\r\n    }\r\n\r\n    public String generatePerishableToken() {\r\n        final UUID uuid = UUID.randomUUID();\r\n        final String toString = uuid.toString();\r\n        final String result = toString.replaceAll(\"-\", \"\");\r\n        return result;\r\n\t}\r\n    \r\n    public int lengthOf(StringBuilder to){\r\n        // The trick here is the casting to CharSequence,\r\n        // this is to test that the runtime type(StringBuilder) is checked for mocked calls and not\r\n        // the compile-time type (CharSequence)\r\n        return lengthOf((CharSequence) to);\r\n\t}\r\n\t\r\n    private int lengthOf(CharSequence to){\r\n        return to.length();\r\n    }\r\n}\r\n"
  },
  {
    "path": "tests/utils/src/main/java/samples/whitebox/ClassWithPowerMockGeneratedConstructor.java",
    "content": "/*\n * Copyright 2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage samples.whitebox;\n\nimport org.powermock.core.IndicateReloadClass;\n\n/**\n * Class that simulates a PowerMock generated constructor.\n */\npublic class ClassWithPowerMockGeneratedConstructor {\n\tpublic ClassWithPowerMockGeneratedConstructor(String string) {\n\t}\n\n\t/**\n\t * Simulates a PowerMock generated constructor.\n\t */\n\tpublic ClassWithPowerMockGeneratedConstructor(IndicateReloadClass indicateReloadClass) {\n\t}\n}\n"
  },
  {
    "path": "version.properties",
    "content": "#Currently building version\nversion=2.0.10\n\n#Prevoius version used to generate release notes delta\npreviousVersion=2.0.9\n"
  }
]